15
votes

I'd like to create a Mongoose Schema that validates the object below with the following restrictions:

  • field2 is optional (0-1 relationship),
  • field2.type is required if field2 exists (notice that the name of the field is "type" as mongoose reserved word for type definitions),
  • field2 and the the base object must be in the same document.

Code example

{
  field1: "data",
  field2: {
    type: "data",
    data: "data"
  }
}

Thanks in advance.

4
Mongoose nested validation is buggy at best. I'd recommend writing your own validation if you're using nested stuff. See github.com/Automattic/mongoose/issues/1919 - Chris Houghton
@ChrisHoughton thank you. I found Mongoose quite buggy and incomplete. I am considering moving to mongodb driver and code the constrains and validations. - Víctor Herraiz

4 Answers

20
votes

You can refer to this answer:

{
  field1: "your data",
  field2: {
    type: {
      "your data"
    },
    required: false
  }
}

So an example would be:

{
  field1: String,
  field2: {
    type: {
      nestedField1: { type: String, required: true },
      nestedField2: String
    },
    required:false
  }
}

If field2 exists, then nestedField1 would be required.

8
votes

@Mina Michael answer didn't worked for me but, when i tweaked a little it worked for me. I tried it like this:

{
  field1: String,
  field2:{
    type: new Schema({
      nestedField1: {type:Boolean,required:true},
      nestedField2: String,
    }),
    required: false
  }
}
0
votes

you may mean something like this:

var Field2Schema = new mongoose.Schema({
  type: { type: String, required: true },
  data: String
});

var MainSchema = new mongoose.Schema({
  field1: String,
  field2: Field2Schema
});
0
votes

how to insert data with this schema to db.. mainly those nested fields...employee.namefirst = req.body.namefirst;

//first = req.body.namefirst;
employee.name.middle = req.body.namemiddle;
employee.name.last = req.body.namelast;