简体   繁体   English

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

[英]Joi is throwing error while validating mongoose object -

When I create an object of type Contact (which is a model of MongoDB schema) it throws some weird error as below.当我创建一个 Contact 类型的对象(它是 MongoDB 模式的模型)时,它会抛出一些奇怪的错误,如下所示。 My purpose of using Joi is for Client-side validation aka incoming request.我使用 Joi 的目的是用于客户端验证,即传入请求。

Here auth is a middleware that is validating jwt and fetching out the id from jwt.这里 auth 是一个中间件,它验证 jwt 并从 jwt 中取出 id。

It is showing weird kind of error like - **"$__" is not allowed.它显示了一种奇怪的错误,例如 - **"$__" 是不允许的。 "isNew" is not allowed.不允许使用“isNew”。 "errors" is not allowed.不允许出现“错误”。 "_doc" is not allowed.不允许使用“_doc”。 "$locals" is not allowed.不允许使用“$locals”。 "$op" is not allowed **不允许使用“$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}`);
}

在此处输入图片说明

在此处输入图片说明

在此处输入图片说明

The problem is that you are trying to validate the mongoose schema class which has its own internal properties.问题是您正在尝试验证具有自己内部属性的猫鼬模式类。 That is what you are seeing in the error.这就是您在错误中看到的内容。 You have two choices here你在这里有两个选择

  • Instead of passing contact object, pass req.body to your validate function.不要传递联系人对象,而是将req.body传递给您的验证函数。

  • Or extract properties from contact schema and pass that object to validate function.或者从联系模式中提取属性并将该对象传递给验证函数。

Hope that helps.希望有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM