1
votes

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
     }
  });
3

3 Answers

0
votes

I have a example where i put small validation in my moongoose schema, hope it may help.

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;

Like this, you can add further validation. In your mongo query, just check

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

Try this

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

Required Validators On Nested Objects

mongoose docs actually suggest to use nested schema, so we can do validation on an object.

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
  }
};

This should do the tricks and do validation.