Reputation: 360
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.
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.
Upvotes: 1
Views: 892
Reputation: 595
You don't save the embedded document as the whole document inside another document. You'll have to save the '_id' of the document and at the time of fetching the record, you'll call populate()
on the query.
So, let us suppose you have to save document in Cupboard schema, the schema will look like this -
var CupboardSchema = new Schema({
cupboard_name: {
type: String,
required: true,
unique: true
},
cupboard_desc: {
type: String,
required: true
},
shelf: {
type: Schema.Types.ObjectId,
ref: 'ShelfSchema'}
},
{
timestamps: true
});
Now, at 'shelf' save the corresponding document, that you want to populate. And when you will be fetching the document, call populate()
like -
CupboardSchemaModel.find({_id: <some-id-you-want-to-fetch>}).populate('shelf');
Upvotes: 1