猫鼬findOneAndUpdate和runValidators无法正常工作 [英] Mongoose findOneAndUpdate and runValidators not working

查看:81
本文介绍了猫鼬findOneAndUpdate和runValidators无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在尝试使'runValidators'选项起作用时遇到问题.我的用户架构中有一个电子邮件字段,该字段必须设置为true,但是每次将新用户添加到数据库中(使用"upsert"选项)并且该电子邮件字段为空时,它不会抱怨:

I am having issues trying to get the 'runValidators' option to work. My user schema has an email field that has required set to true but each time a new user gets added to the database (using the 'upsert' option) and the email field is empty it does not complain:

 var userSchema = new mongoose.Schema({
   facebookId: {type: Number, required: true},
   activated: {type: Boolean, required: true, default: false},
   email: {type: String, required: true}
});

findOneAndUpdate代码:

model.user.user.findOneAndUpdate(
      {facebookId: request.params.facebookId},
      {
          $setOnInsert: {
              facebookId: request.params.facebookId,
              email: request.payload.email,
          }
      },
      {upsert: true, 
       new: true, 
       runValidators: true, 
       setDefaultsOnInsert: true
      }, function (err, user) {
          if (err) {
              console.log(err);
              return reply(boom.badRequest(authError));
          }
          return reply(user);
      });

我不知道我在做什么错,我只是遵循了文档: http://mongoosejs.com/docs/validation .html

I have no idea what I am doing wrong, I just followed the docs: http://mongoosejs.com/docs/validation.html

在文档中是这样说的:

请注意,在猫鼬4.x中,更新验证器仅在$ set和$ unset操作上运行.例如,无论number的值如何,以下更新都将成功.

Note that in mongoose 4.x, update validators only run on $set and $unset operations. For instance, the below update will succeed, regardless of the value of number.

我将$ setOnInsert替换为$ set,但结果相同.

I replaced the $setOnInsert with $set but had the same result.

推荐答案

仅当您尝试显式$ unset键时,必需的验证器才会失败.

required validators only fail when you try to explicitly $unset the key.

这对我来说毫无意义,但这就是文档所说的.

This makes no sense to me but it's what the docs say.

这篇关于猫鼬findOneAndUpdate和runValidators无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆