Sorry if this is obvious, but I googled for hours and most result is related to sub-document/nested-schema, which is for array of object and not my case.
For simplicity, I just construct a minimal object, but the concept is the same.
I have a mongoose Schema as follow, I want to validate father object by validateFunction, which the validateFunction is just checking if firstName/lastName exists or not:
var PersonSchema = new Schema({
firstName : String,
lastName : String,
father : {
firstName: String,
lastName: String
},
mother : {
firstName: String,
lastName: String
}
};
I have tried
var PersonSchema = new Schema({
firstName : String,
lastName : String,
father : {
type: {
firstName: String,
lastName: String
},
validate : validateFunction
},
mother : {
firstName: String,
lastName: String
}
};
Which seems to work, but after reading Mongoose Schema Type, it seems the type is not a valid type in mongoose.
Can someone point me the proper way to add validation on a child object(father)?
Note: I have check this SO which is similar, but I don't want to store 'father' in a separate collection as the Person is the only object that use 'father', so I think father so be inside 'Person' object.
Edit: I have tested @Azeem suggestion with the following code:
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);
})
and got 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
if the schema is changed to the following one, it works (prove of validate function running properly)
var PersonSchema2 = new Schema({
firstName : String,
lastName : String,
father : {
firstName: String,
lastName: {type : String ,validate : many}
},
mother : {
firstName: String,
lastName: String
}
});