Node.js MongoDB/mongoose-未保存嵌套文档
我有4种型号,Node.js MongoDB/mongoose-未保存嵌套文档,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,我有4种型号,网格,容器,行和列。我需要初始化一个网格,其中嵌套了3个模型的其余部分 我遇到的问题是,创建了对容器、行和列的引用(ObjectId),但没有保存文档本身。仅保存网格文档 我希望它能将其余的模型保存到各自的集合中 我错过了什么 以下是我的模型/模式: const GridSchema = new Schema({ container: {type: mongoose.Schema.Types.ObjectId, ref: 'Container', required: true}
网格
,容器
,行
和列
。我需要初始化一个网格
,其中嵌套了3个模型的其余部分
我遇到的问题是,创建了对容器
、行
和列
的引用(ObjectId
),但没有保存文档本身。仅保存网格
文档
我希望它能将其余的模型保存到各自的集合中
我错过了什么
以下是我的模型/模式:
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
});
当然,不会保存嵌套文档,因为您没有调用它们的
.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请检查并告知编辑的部分是否有助于回答您的问题。