Wednesday, 5 April 2017

Mongoose can't save embedded documents

I am trying to create a document in Mongo DB which has an embedded document within it. The model/schema for the document is as follows:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

// Cupboard Collection Schema
 var ShelfSchema = new Schema({
 shelf_name: {
    type: String
 },
 shelf_desc: {
    type: String
 }
});

var CupboardSchema = new Schema({
 cupboard_name: {
  type: String,
  required: true,
  unique: true
 },
cupboard_desc: {
 type: String,
 required: true
},
shelf: [ShelfSchema]
},
{
  timestamps: true
});

module.exports = mongoose.model('Cupboard', CupboardSchema);

Image shows the code for saving the document. Code for saving document

When i print the "newCupboard" in console, I am getting the document in exact format as follows:

{
_id: 58e4b972931dc809f4127b0b
cupboard_name: Cupboard A,
cupboard_desc: Cupboard A Details,
shelf: [ {
 shelf_name: Cupboard A,
 shelf_desc: Cupboard A Details,
 _id: 58e4c2742bfc0111dc47f149
 }]
}

But after the execution, the embedded document is not getting saved & no error is shown. Final result is as shown below:

{
 _id: 58e4b972931dc809f4127b0b
 cupboard_name: Cupboard A,
 cupboard_desc: Cupboard A Details
}

Can anybody help me to figure this out, why the embedded doc is not getting saved in mongo db ?

Thanks.



via Roger Jacob

No comments:

Post a Comment