0

Hi MongooseJS experts!

I'm new in MongooseJS, This is my 2nd day of solving this problem but I can't find a working solution to this.

Thank you in advance!

My Delete method

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

Schema

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

Sample JSON

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

Error message

Cannot use the part (_id) of (content.items._id) to traverse the element ({items: [{ _id: "SAMPLE_ID", title: "SAMPLE TITLE"}] })
4
  • What's the problem ? Is there any error message ? Can you include the Schema for the Document ? Commented Nov 3, 2021 at 7:09
  • Hi there, the error message is Cannot use the part (_id) of (content.items._id) to traverse the element ({items: [ { _id: "SAMPLE_ID", title: "SAMPLE TITLE"} ]}) Commented Nov 3, 2021 at 7:13
  • you couldn't remove _id because its required Commented Nov 3, 2021 at 7:47
  • Hi @mohammad, wdym by that? Commented Nov 3, 2021 at 7:50

1 Answer 1

2

you should use like this

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

https://mongoplayground.net/p/Ou26tab2mBU

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.