有没有办法通过 Mongoose 中的查询来更新文档数组中的对象?

Is there a way to update an object in an array of a document by query in Mongoose?

我有一个数据结构:


{
  field: 1, 
  field: 3,
  field: [
    { _id: xxx , subfield: 1 },
    { _id: xxx , subfield: 1 },
  ] 
}

我需要更新数组中的某个元素。

到目前为止,我只能通过拉出旧对象并推入新对象来做到这一点,但它会改变文件顺序。

我的实现:

            const product = await ProductModel.findOne({ _id: productID });
            const price = product.prices.find( (price: any) => price._id == id );

            if(!price) {
                throw {
                    type: 'ProductPriceError',
                    code: 404,
                    message: `Coundn't find price with provided ID: ${id}`,
                    success: false,
                }
            }

            product.prices.pull({ _id: id })
            product.prices.push(Object.assign(price, payload))
            await product.save()

我想知道是否有任何原子方法来实现它。因为这种方法似乎并不安全。

是的,如果可以找到数组中的特定对象,您可以更新它。 看一下位置 '$' 运算符 here.

您当前使用 mongoose 的实现将有点像这样:

 await ProductModel.updateOne(
      { _id: productID, 'prices._id': id },//Finding Product with the particular price
      { $set: { 'prices.$.subField': subFieldValue } },
 );

注意 prices.$.subField 中的“$”符号。 MongoDB 足够聪明,只更新查询找到的索引处的元素。