【问题标题】:MongoDB/mongoose - Nested documents are not being savedMongoDB/mongoose - 嵌套文档没有被保存
【发布时间】:2018-06-30 08:04:50
【问题描述】:

我有 4 个模型,GridContainerRowColumn。我需要初始化一个Grid,并将其余 3 个模型嵌套在其中。

我遇到的问题是创建了对ContainerRowColumn 的引用(ObjectIds),但文档本身没有保存。仅保存Grid 文档。

我希望它将其余模型也保存到各自的集合中......

我错过了什么?

这是我的模型/模式:

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);

这是我如何初始化网格并保存它:

  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
  });

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    当然不会保存嵌套文档,因为您没有调用他们的 .save() 调用。

    另外,不要像这样创建 then,而是单独创建 then,然后使用它们的引用或变量来处理。这将使您的工作更轻松、更清洁。

    编辑:指定如何一次进行多次保存。

    你可以这样做:

    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() 对于像这样保存多个文档非常有用。由于MongoDB没有支持事务的功能。

    对于迟到的回复,我深表歉意。

    【讨论】:

    • 但是如果保存其中一个失败怎么办?你怎么处理?如果一个失败了,那么其他的就不应该被保存。
    • @chrillewoodz 请检查并判断编辑的部分是否有助于您回答问题。
    猜你喜欢
    • 2015-07-03
    • 2014-11-09
    • 2012-10-17
    • 2011-11-10
    • 2021-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-15
    相关资源
    最近更新 更多