这是我的模型:
'use strict';
var nested = new Schema({
name: String
});
var test = new Schema({
url : {
type : String,
// First validation
validate : [validator.isURL, 'Invalid URL']
},
array : [
{
type: nested,
// Second Validation
validate: [function(value) {console.log("CALLED"); return value.length <=3;}, 'Too long']
}
]
});
module.exports = Parent.discriminator('Test', test);;
Run Code Online (Sandbox Code Playgroud)
这是我创建新文档的方法:
Test.findOrCreate({url: url}, function(err, model, created) {
if (created) {
model.array = whatever;
}
model.save(function(err) {
if (err) {return res.status(422).json(err);}
next();
});
});
Run Code Online (Sandbox Code Playgroud)
这是更新:
Test.findByIdAndUpdate(id, {$set: {array: whatever}}, {new: true, runValidators: true}, function(err, model) {
if (err) {
return res.status(422).json(err);
}
res.status(200).json(model);
});
Run Code Online (Sandbox Code Playgroud)
假设whatever在两种情况下(新的和更新的)都包含一个长度为 4 的数组。
创建新模型时,两个验证都按预期工作,但出现错误。但是,当使用 时findByIdAndUpdate,只运行第一个验证并且array忽略属性上的验证(它甚至没有被调用)。是什么赋予了?
根据文档,验证器似乎仅适用于update()并且findOneAndUpdate()如果runValidators设置为true。
你有没有尝试过:
Test.findOneAndUpdate({_id: id}, {$set: {array: whatever}}, {new: true, runValidators: true}, function(err, model) {
if (err) {
return res.status(422).json(err);
}
res.status(200).json(model);
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4518 次 |
| 最近记录: |