【问题标题】:MongooseJS: How to remove 1 object inside Array in Array of ObjectsMongooseJS:如何在对象数组中删除 1 个对象
【发布时间】:2021-11-03 06:31:48
【问题描述】:

您好 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"}] })

【问题讨论】:

  • 有什么问题?有任何错误信息吗?您可以包含文档的架构吗?
  • 您好,错误信息是Cannot use the part (_id) of (content.items._id) to traverse the element ({items: [ { _id: "SAMPLE_ID", title: "SAMPLE标题"} ]})
  • 您无法删除 _id,因为它是必需的
  • 嗨@mohammad,wdym 吗?

标签: javascript node.js mongodb express mongoose


【解决方案1】:

你应该这样使用

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

https://mongoplayground.net/p/Ou26tab2mBU

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-01-16
    • 1970-01-01
    • 1970-01-01
    • 2018-08-07
    • 2019-04-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多