Joi在验证猫鼬对象时抛出错误-

问题描述 投票:0回答:2

[当我创建Contact类型的对象(这是MongoDB模式的模型)时,它会引发一些奇怪的错误,如下所示。我使用Joi的目的是用于客户端验证(即传入请求)。

这里auth是一个中间件,它正在验证jwt并从jwt中获取id。

它显示出一种奇怪的错误,例如-**“ $ __”是不允许的。不允许使用“ isNew”。不允许“错误”。不允许使用“ _doc”。不允许使用“ $ locals”。不允许使用“ $ op” **

router.post('/',auth,async (req,res)=>{
try{
// console.log(`contact - ${JSON.stringify(req.body)}`);
let contact = new Contact({
  firstName : req.body.firstName,
  lastName : req.body.lastName,
  email : req.body.email,
  address : req.body.address,
  country : req.body.country,
  isBookMark : req.body.isBookMark,
});
// console.log(`before contact - ${JSON.stringify(contact)}`);
// // contact = {...req.body};
// console.log(`before after - ${JSON.stringify(contact)}`);
contact.userID=req.user.id;
// ?console.log(`contact - ${(contact)}`);

const {error} = validateContact(contact);
console.log(`ERROR - ${error}`);
}
 catch(error){
console.log(`contacts - ${error.message}`);
}

enter image description here

enter image description here

enter image description here

javascript node.js mongodb express
2个回答
1
投票

问题是,您正在尝试验证具有其内部属性的猫鼬模式类。那就是您在错误中看到的内容。您有两种选择]

  • 代替传递联系人对象,传递req.body到您的验证函数。

  • 或从联系模式中提取属性,然后将该对象传递以验证功能。

希望有所帮助。


0
投票
const contact = new mongoose.Schema({
userId: {
   type:mongoose.Schema.Types.ObjectId,
   ref:'user',
   type:'true
}

名字,姓氏和类别的名称相同

现在将文件导出为module.export = mongoose.model('contact', contact);会有所帮助

© www.soinside.com 2019 - 2024. All rights reserved.