我正在尝试执行验证而不保存。 API文档显示有一个validate method ,但它似乎对我不起作用。
这是我的架构文件:
var mongoose = require("mongoose");
var schema = new mongoose.Schema({
mainHeading: {
type: Boolean,
required: true,
default: false
},
content: {
type: String,
required: true,
default: "This is the heading"
}
});
var moduleheading = mongoose.model('moduleheading', schema);
module.exports = {
moduleheading: moduleheading
}
..然后在我的 Controller 中:
var moduleheading = require("../models/modules/heading").moduleheading; //load the heading module model
var ModuleHeadingo = new moduleheading({
mainHeadin: true,
conten: "This appears to have validated.."
});
ModuleHeadingo.validate(function(err){
if(err) {
console.log(err);
}
else {
console.log('module heading validation passed');
}
});
您可能会注意到,我传入的参数称为“mainHeadin”和“conten”,而不是“mainHeading”和“content”。但是,即使我调用 validate() 它也不会返回错误。
我显然错误地使用了验证 - 有什么提示吗? mongoose 文档实在是太缺乏了!
提前致谢。
最佳答案
您的验证永远不会失败,因为您已在架构中为 mainHeading
和 content
创建了默认属性。换句话说,如果您没有设置这些属性中的任何一个,Mongoose 将分别默认它们为 false
和 “这是标题”
- 即它们将始终被定义。
删除默认属性后,您会发现 Document#validate 将按照您最初的预期工作。针对您的架构尝试以下操作:
var schema = new mongoose.Schema({
mainHeading: {
type: Boolean,
required: true
},
content: {
type: String,
required: true
}
});
关于node.js - Mongoose ODM - 验证失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20606372/