Mongoose ODM - 未能验证

时间:2013-12-16 08:29:29

标签: node.js mongoose

我正在尝试执行验证而不保存。 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
}

..然后在我的控制器中:

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文档确实缺乏!

提前致谢。

1 个答案:

答案 0 :(得分:2)

您的验证永远不会失败,因为您已在架构中为mainHeadingcontent创建了默认属性。换句话说,如果您没有设置其中任何一个属性,Mongoose会将它们分别默认为false"This is the heading" - 即它们将始终被定义。

删除默认属性后,您会发现Document#validate将按您最初的预期运行。请尝试以下方案:

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