如何在模式中的mongoose子元素上添加验证?

时间:2016-07-19 07:20:08

标签: node.js validation mongoose

很抱歉,如果这很明显,但我用Google搜索了几个小时,大部分结果与子文档/嵌套模式有关,这是针对对象数组而不是我的情况。

为简单起见,我只是构造一个最小的对象,但概念是相同的。

我有一个mongoose Schema如下,我想通过validateFunction验证父对象,validateFunction只是检查firstName / lastName是否存在:

var PersonSchema = new Schema({
  firstName : String,
  lastName : String, 
  father : {
    firstName: String,
    lastName: String
 }, 
  mother : {
    firstName: String,
    lastName: String
 }
};

我试过了

var PersonSchema = new Schema({
  firstName : String,
  lastName : String, 
  father : {
    type: {
      firstName: String,
      lastName: String
    },
    validate : validateFunction
  }, 
  mother : {
    firstName: String,
    lastName: String
  }
};

这似乎有效,但在阅读Mongoose Schema Type后,似乎该类型在mongoose中不是有效类型。

有人能指出我在子对象(父亲)上添加验证的正确方法吗?

注意:我检查了这个类似的SO,但我不想将'father'存储在一个单独的集合中,因为Person是唯一使用'father'的对象,所以我认为父亲所以在'人'对象里面。

编辑:我已使用以下代码测试了@Azeem建议:

var log = function (val) {
    console.log(val);
    return true ;
}
var validateFunction = function (val) {
    if (typeof val === 'undefined') {
        return false;
    }
    console.log(typeof val, val);
    return true;
}
var many = [
    { validator: log, msg: 'fail to log' },
    { validator: validateFunction, msg: 'object is undefined' }
];
var PersonSchema = new Schema({
  firstName : String,
  lastName : String, 
  father : {
    firstName: String, 
    lastName: {type : String }
    validate : many // following http://mongoosejs.com/docs/api.html#schematype_SchemaType-validate
  }, 
    mother : {
    firstName: String,
    lastName: String
     }
  });

var PersonModel = mongoose.model("PersonTest", PersonSchema);

var josephus = new PersonModel({firstName:'Josephus', father:{lastName:null}});
josephus.save(function(error) {
    console.log("testing", error);
})

并收到错误

***/index.js:34
    validate : many
    ^^^^^^^^
SyntaxError: Unexpected identifier
    at Module._compile (module.js:439:25)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)
    at node.js:945:3

如果架构更改为以下架构,则可以正常运行(证明验证功能正常运行)

var PersonSchema2 = new Schema({
  firstName : String,
  lastName : String, 
  father : {
    firstName: String, 
    lastName: {type : String ,validate : many}

  }, 
    mother : {
    firstName: String,
    lastName: String
     }
  });

3 个答案:

答案 0 :(得分:0)

我有一个例子,我在我的moongoose架构中进行了小验证,希望它可能有所帮助。

var UserType = require('../defines/userType');
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

//Schema for User
var UserSchema = new Schema({
     name: {
          type: String,
          required: true
     },
     email: {
          type: String
     },
     password: {
          type: String,
          required: true
     },
     dob: {
          type: Date,
          required: true
     },
     gender: {
          type: String, // Male/Female
          required: true
          default: 'Male'
     },
     type: {
         type: Number,
         default: UserType.User
     },

    address:{
        streetAddress:{
             type: String,
             required: true
        },
        area:{
             type: String
        },
        city:{
             type: String,
             required: true
        },
        state:{
             type: String,
             required: true
        },
        pincode:{
             type: String,
             required: true
        },
    },
    lastLocation: {
        type: [Number], // [<longitude>, <latitude>]
        index: '2d',    // create the geospatial index
        default: [77.2166672, 28.6314512]
    },
    lastLoginDate: {
        type: Date,
        default: Date.now
    },

});

//Define the model for User
var User;
if(mongoose.models.User)
    User = mongoose.model('User');
else
    User = mongoose.model('User', UserSchema);

//Export the User Model
module.exports = User;

像这样,您可以添加进一步的验证。在你的mongo查询中,只需检查

db.collection.validate(function(err){
     if(err){
          console.log(err);    //if your validation fails,you can see the error.   
     }
});

答案 1 :(得分:0)

试试这个

 var PersonSchema = new Schema({
  firstName : String,
  lastName : String, 
    father : {
    firstName: String, 
    lastName: String  
    validate : validateFunction
  }, 
    mother : {
    firstName: String,
    lastName: String
     }
  };

答案 2 :(得分:0)

Required Validators On Nested Objects

mongoose docs实际上建议使用嵌套模式,因此我们可以对对象进行验证。

var ParentSchema = new Schema({
    firstName: String,
    lastName: String
 });
var PersonSchema = new Schema({
  firstName : String,
  lastName : String, 
  father : {
    type: ParentSchema, 
    validate : validateFunction
  }, 
  mother : {
    type: ParentSchema, 
    validate : validateFunction
  }
};

这应该做一些技巧并进行验证。