Thursday, 16 July 2015

nodejs Mongoose sub documents, nested schema



You can do by two ways:

var subDoc = new Schema({
  name: String
});

var mainDoc = newSchema({
  names: [subDoc]
});
or
var mainDoc = newSchema({
  names: [{
    name: String
 }]
});

You sub document will get a extra "_id" 

{
    _id: "mainId"
    names: [      {
        _id: "unwantedId",
        name: "value"
      },
      {
        _id: "unwantedId",
        name: "value"
      }
    ]
}


To remove this _id, you can:

var subDoc = mongoose.Schema({     name: String
},{ _id : false });

or 

var mainDoc = newSchema({
  names: [{
    name: String, id: false
 }]
});




http://mongoosejs.com/docs/subdocs.html

http://stackoverflow.com/questions/15208711/mongoose-subdocuments-vs-nested-schema

http://stackoverflow.com/questions/17254008/stop-mongoose-from-created-ids-for-subdocument-arrays

No comments:

Post a comment