如何使用Mongoose更新MongoDB中具有数组数组的文档?

问题描述 投票:0回答:1

给定以下架构:

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如果是这样,怎么样?

node.js mongodb mongoose
1个回答
1
投票

您可以将findOneAndUpdatearrayFilters一起使用:

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);
    }
);
© www.soinside.com 2019 - 2024. All rights reserved.