【发布时间】:2017-01-03 01:28:53
【问题描述】:
首先,this 没有帮助。
假设我们有一个用户模型:
const schema = new mongoose.Schema({
active: { type: Boolean },
avatar: { type: String }
});
const User = mongoose.model('User', schema);
当我们更新它时(设置头像):
// This should pass validation
User.update({ _id: id }, { $set: { avatar: 'user1.png' } });
我们希望根据当前(或更改的)active 属性值对其进行验证。
案例#1
-
active是false - 我们不应该能够设置头像 - 它不应该通过验证
案例#2
-
active是true - 我们应该能够设置头像 - 它应该通过验证
想法
- 使用自定义验证器
const schema = new mongoose.Schema({
active: { type: Boolean },
avatar: { type: String, validate: [validateAvatar, 'User is not active'] }
});
function validateAvatar (value) {
console.log(value); // user.avatar
console.log(this.active); // undefined
}
所以这不起作用,因为我们无权访问active 字段。
- 使用预“验证”挂钩
schema.pre('validate', function (next) {
// this will never be called
});
此钩子不适用于update 方法。
- 使用预“更新”挂钩
schema.pre('update', function (next) {
console.log(this.active); // undefined
});
这对我们不起作用,因为它无法访问模型字段。
- 使用发布“更新”挂钩
schema.post('update', function (next) {
console.log(this.active); // false
});
这个可行,但在验证方面不是很好的选择,因为该函数仅在模型已保存时才被调用。
问题
那么有没有办法在使用model.update() 方法的同时,在保存模型之前根据几个字段(保存在数据库和新字段中)验证模型?
总结一下:
- 初始用户对象
{ active: false, avatar: null }
- 更新
User.update({ _id: id }, { $set: { avatar: 'user1.png' } });
- 验证应该有权访问
{ active: false, avatar: 'user1.png' }
- 如果验证失败,则不应将更改传递给 DB
【问题讨论】:
标签: javascript node.js mongodb validation mongoose