猫鼬 findOneAndUpdate 和 runValidators 不起作用 [英] Mongoose findOneAndUpdate and runValidators not working
问题描述
我在尝试使用runValidators"选项时遇到问题.我的用户架构有一个电子邮件字段,该字段已将 required 设置为 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
在文档中是这样说的:
请注意,在 mongoose 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.
我用 $set 替换了 $setOnInsert 但结果相同.
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屋!