0
votes

I'm using this code for removing a particular array element stored in MongoDB when clicked that from the app. But this code is not working.

schema structure looks like this -

const tagsSchema = new Schema({ category: { type: String, required: true }, tname: { type: Array } }, { _id: true });

Below is the code I'm using for removing array element from db -

Tags.updateOne({ tname: req.params.name }, { $pull: { _id: [req.params.id] } })

For example - "tname": "technical", "nontechnical"

Now, technical is being clicked in the app to remove, but with the code I'm using it's not getting removed.

2
Welcome to Stack Overflow! Please provide more information about what you have tried to resolve your problem. What do you mean by "not working?" Is there a particular error? It's also helpful to provide more code as context. - slasky
I'm not getting any specific error but not able to remove the selected element, and getting that selected element as undefined in terminal. I don't know if that piece of code is right for removing an array element - Garry

2 Answers

0
votes

you can use directly your element_value without [] after your array field, like below..

Tags.updateOne({tname: req.params.name}, { $pull: { your_array_field: req.params.id } } )
0
votes

You have to find the specific tag by its "_id" and then remove the particular name from the "tname" array.

Tags.updateOne({ _id: req.params.id }, { $pull: { tname: req.params.name } })