Node.js Mongoose ODM-无法验证
我试图在不保存的情况下执行验证。API文档显示存在一个问题,但它似乎不适合我 这是我的模式文件:Node.js Mongoose ODM-无法验证,node.js,mongoose,Node.js,Mongoose,我试图在不保存的情况下执行验证。API文档显示存在一个问题,但它似乎不适合我 这是我的模式文件: var mongoose = require("mongoose"); var schema = new mongoose.Schema({ mainHeading: { type: Boolean, required: true, default: false }, content: { type: String, requ
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
}
…然后在我的控制器中:
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文档真的很缺乏
提前感谢。您的验证将永远不会失败,因为您已经为架构中的
main-heading
和content
创建了默认属性。换句话说,如果您不设置这些属性中的任何一个,Mongoose将分别将它们默认为false
和“这是标题”
——也就是说,它们将始终被定义
删除默认属性后,您会发现文档#validate将按照最初的预期工作。请针对您的架构尝试以下操作:
var schema = new mongoose.Schema({
mainHeading: {
type: Boolean,
required: true
},
content: {
type: String,
required: true
}
});
当场,似乎真的很简单,当你看它的方式!