mongooseODM – 未能validation

我试图执行validation而不保存。 API文档显示有一个validation方法 ,但它似乎并没有为我工作。

这是我的模式文件:

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()时也不会返回错误。

我显然使用不正确的validation – 任何提示? mongoose的文件是真的缺乏!

提前致谢。

您的validation永远不会失败,因为您已经为模式中的mainHeadingcontent创build了默认属性。 换句话说,如果你不设置这两个属性中的任何一个,Mongoose将默认它们为false并且"This is the heading" ,也就是说它们将被定义。

一旦你删除了默认的属性,你会发现Document#validate将按照你最初的预期工作。 为您的模式尝试以下内容:

 var schema = new mongoose.Schema({ mainHeading: { type: Boolean, required: true }, content: { type: String, required: true } });