Delete object from nested array by id

I just can’t seen to get this thing to work. I have this data set:

{
  _id: new ObjectId("64301d2402240ae566748671"),
  user_id: new ObjectId("6426fae9ff0a6b4366bfb471"),
  queries: [
    {
      text: 'ovo je rtestset',
      _id: new ObjectId("64301f1402240ae5667486c5")
    },
    {
      text: 'ads fasdf asd f',
      _id: new ObjectId("64314dad9078b3cbf3bb583c")
    },
    {
      text: 'sadf asdf asdf ',
      _id: new ObjectId("6431518c9078b3cbf3bb58d7")
    },
    {
      text: 'asdf asdf asdf asdf ',
      _id: new ObjectId("6431518f9078b3cbf3bb58e0")
    },
    {
      text: 'asdf asdf asdf asdf ',
      _id: new ObjectId("643151929078b3cbf3bb58ea")
    }
  ],
  __v: 0
}

I’m try to delete one specific query from the nested array based on id. I get the user_id form the session and the query id from req.query. My attempts were as follows:

1. Queries.updateOne({"user_id": user.id}, {$pull: {"queries.$._id": query_id}})
2. Queries.updateOne({"user_id": user.id}, {$pull: {"queries": {"_id": query_id}}})

I’ve tried multiple other options but none with the result I wanted. If I did get the req to get to the db, but it just deletes the last object from the array for some reason.

Any suggestions?

Given the data you shared and assuming that query_id is an ObjectId, the correct form would be

But what I suspect is that query_id is a string rather than an ObjectId while your data is correctly stored as an ObjectId. I would try

Queries.updateOne({"user_id": user.id}, {$pull: {"queries": {"_id": new ObjectId(query_id)}}})`

Yup that’s it, ty man, have a good one.

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.