Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

305
Views
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.

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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');
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!