[英]How to update a document having an array of arrays in MongoDB with Mongoose?
給定以下架構:
const item = {
_id: false,
amount: { type: Number, required: true },
};
const item_schema = new Schema({ item_history: [item] });
const parent_schema = new Schema({
...
items: [item_schema],
...
})
和這個文件在數據庫中
{
...
items: [{ _id: 1, item_history: [{ amount: 10 }] }]
...
}
假設我要使用以下項目更新此文檔:
const changed_or_new_items = [{ _id: 1, amount: 20 }, { amount: 30 }];
這應該導致數據庫中的該對象:
{
...
items: [{ _id: 1, item_history: [{ amount: 10 }, { amount: 20}] },
{ _id: 2, item_history: [{ amount: 30 }] }]
...
}
這是我當前更新文檔的方式:
const parent = await Parent.findOne(some_query).exec();
changed_or_new_items.forEach(item => {
if (!item._id) {
parent.items.push({ item_history: [item] });
}
else {
const item_doc = parent.items.id(item._id);
item_doc.item_history.push(_.omit(item, '_id'));
}
});
await parent.save();
通過使用更新操作(例如findOneAndUpdate
可以實現上述findOneAndUpdate
,如果可以,如何實現?
您可以將findOneAndUpdate
與arrayFilters
一起使用:
Parent.findOneAndUpdate(
{ 'items._id': 1 },
{ '$set': { 'items.$.item_history.$[element].amount': 30 } },
{
'arrayFilters': [ {'element.amount': 20} ],
'new': true,
'upsert': true
}, (err, updatedParent ) => {
if (err) res.status(400).json(err);
res.status(200).json(updatedParent);
}
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.