首页 > 解决方案 > MongooseJS:如何在对象数组中删除 1 个对象

问题描述

MongooseJS专家!

我是MongooseJS的新手,这是我解决这个问题的第二天,但我找不到一个可行的解决方案。

先感谢您!

我的删除方法

Cart.updateOne(
    { "content.merchantId": req.body.merchantId },
    { $pull: { "content.items._id": req.body.productId } },
    { new: true },
    function (error, result) {
      if (error) { }
      else if (result) { }
    }
);

架构

const CartSchema = new Schema({
      customerId: {
        type: String,
        required: true,
      },
      content: {
        merchantName: {
          type: String,
          required: true,
        },
        merchantId: {
          type: String,
          required: true,
        },
        items: [],
      },
});

示例 JSON

[
    {
        "content": {
            "merchantName": "SAMPLE_MERCHANT_NAME",
            "merchantId": "SAMPLE_MERCHANT_ID",
            "items": [
                {
                    "_id": "SAMPLE_ID",
                    "title": "SAMPLE TITLE",
                }
            ]
        },
        "_id": "618220e83966345ab5d451cd",
        "__v": 0
    },
]

错误信息

Cannot use the part (_id) of (content.items._id) to traverse the element ({items: [{ _id: "SAMPLE_ID", title: "SAMPLE TITLE"}] })

标签: javascriptnode.jsmongodbexpressmongoose

解决方案


你应该这样使用

db.collection.update({
  "content.merchantId": "SAMPLE_MERCHANT_ID"
},
{
  $pull: {
    "content.items": {
      "_id": "SAMPLE_ID"
    }
  }
},
{
  new:true
},
)

https://mongoplayground.net/p/Ou26tab2mBU


推荐阅读