简体   繁体   中英

Unable to remove item from array using Mongoose / UpdateOne

I have a Node.js application in which I am trying to remove an object from an array when an API endpoint is hit. I so far have been unable to get it to update/remove the object. Currently, the below query returns with no error but upon checking into my DB I am still seeing it. Below is my query and basic response (I will be adding more but that is outside the scope of this question). I have also included a sample of my data model. In the below data model I am trying to remove the whole object from the foo array as it is no longer needed. Code

const ID = req.params.id
await FooBar.updateOne({foo: {$elemMatch: {v_code: ID}}}, { $pull: {v_code: ID}}, (err) => {
   if(err) return res.json({success: false, err})
   return res.json({success: true, id: ID})
})

Data model

{
  bar: [
     {
       foo: [
         {
             v_code: <>
             _id: <>
          }
       ]
     }
  ]
}

I'm sure this has been asked for in other questions but none specific to my data model. I've tried piecing together multiple SO posts and that is how I got the $elemmatch and the $pull portions of my query and so far I've had zero luck

give the following command a try:

db.collection.updateOne(
    {
        "bar.foo.v_code": ID
    },
    {
        $pull: { bar: { foo: { $elemMatch: { v_code: ID } } } }
    }
)

https://mongoplayground.net/p/iqJki-mnHSJ

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM