Chrillewoodz
Chrillewoodz

Reputation: 28368

MongoDB/mongoose - Nested documents are not being saved

I've got 4 models, Grid, Container, Row and Column. I need to init a Grid with the rest of the 3 models nested in it.

The problem I'm having is that references to Container, Row and Column are created (ObjectIds), but the documents themselves aren't saved. Only the Grid document is saved.

I would expect it to save the rest of the models to their respective collections as well...

What am I missing?

Here are my models/schemas:

const GridSchema = new Schema({
  container: {type: mongoose.Schema.Types.ObjectId, ref: 'Container', required: true}
});

const ContainerSchema = new Schema({
  rows: [{type: mongoose.Schema.Types.ObjectId, ref: 'Row'}]
});

const RowSchema = new Schema({
  columns: [{type: mongoose.Schema.Types.ObjectId, ref: 'Column'}]
});

const ColumnSchema = new Schema({
  modules: [{type: mongoose.Schema.Types.ObjectId, ref: 'Module'}]
});

const Grid = mongoose.model('Grid', GridSchema);
const Container = mongoose.model('Container', ContainerSchema);
const Row = mongoose.model('Row', RowSchema);
const Column = mongoose.model('Column', ColumnSchema);

Here's how I init my grid and saving it:

  const grid = new Grid({
    container: new Container({
      rows: [
        new Row({
          column: [
            new Column({
              modules: []
            })
          ]
        })
      ]
    })
  });

  grid.save((err, grid) => {
     console.log(err, grid); // No error is thrown
  });

Upvotes: 0

Views: 145

Answers (1)

Himanshu Mittal
Himanshu Mittal

Reputation: 612

Ofcourse the nested documents will not be saved, as you are not calling their .save() calls.

Also instead of creating then like this, create then individually, and then use their references or variables to work with. that'll make your work easier and cleaner.

Edit: to specify how to make multiple save at once.

You can do it like this:

column = new Column({
    modules: []
});
row = new Row({
    column: [column._id]
});
container = new Container({
    rows: [row._id]
});
grid = new Grid({
    container
});
Promise.all([column.save(), row.save(), container.save(), grid.save()]).then((docs) => {
    //all the docs are conatined in docs, this is success case, i.e. all document gets saved
    console.log(docs);
}).catch((error) => {
    // handle error here, none of the documents gets saved
    // if saving of anyone of the documents fails, it all gets failed
});

Promise.all() is very useful for saving multiple documents like this. As Mongodb has no feature to support transactions.

And my apologies for late reply.

Upvotes: 1

Related Questions