猫鼬findOneAndUpdate和runValidators无法正常工作

猫鼬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.