1

I am trying to delete object from an array. If the object value match that object will be deleted from the database. Here is my database example:

[{
        _id: "621773f39ec6fe3a3728d686",
        label: "size",
        slug: "size",
        vendor: "admin",
        options: [
            {
                label: "M",
                value: "M"
            },
            {
                label: "XXL",
                value: "XXL"
            },
            {
                label: "XL",
                value: "XL"
            },
            {
                label: "S",
                value: "S"
            }
        ]
    }
    ]

This is my code:

        // DELETE FILED FROM ATTRIBUTE
        app.put('/dashboard/attribute/fieldDelete/:id', async (req, res) => {
            const id = req.params.id
            const { value } = req.body
            unityMartAttributes.updateOne({ value: value }, { $pull: { options: { _id: objectId(id) } } })

        })

Expected output: value: "M" matched that's why that object removed

[{
        _id: "621773f39ec6fe3a3728d686",
        label: "size",
        slug: "size",
        vendor: "admin",
        options: [

            {
                label: "XXL",
                value: "XXL"
            },
            {
                label: "XL",
                value: "XL"
            },
            {
                label: "S",
                value: "S"
            }
        ]
    }
    ]
2
  • what is your issue ? Any specific error ? Commented Mar 17, 2022 at 5:38
  • 1
    need more clarity on the question. what do you want to delete here? Do you want to pull items from options array? do you want to delete the document itself if any match is found on the options array? can you please clarify your use case. thanks! Commented Mar 17, 2022 at 5:46

1 Answer 1

1

You can do it like this:

app.put('/dashboard/attribute/fieldDelete/:id', async (req, res) => {
  const id = req.params.id
  const { value } = req.body

  await unityMartAttributes.updateOne({ "_id": id }, {
    "$pull": {
      "options": {
        "value": value
      }
    }
  });

}

Working example

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

2 Comments

I don't want to delete whole options, I want to delete only one object which is matched with the value
I updated my answer. Can you try it again?

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.