1

So this seems pretty straightforward but I cant seem to get it to work.I have a document in mongodb and i m using mongoose All i need to do is find user by id, get the document and delete one specified object from an array of objects. Here is the Structure:

report:[
   {
     asset_report_id:234,
     name:'somethign,
    },
    {
     asset_report_id:23,
     name:'somethign,
    },
   {
     asset_report_id:111,
     name:'somethign,
    }
]

I tried this :

User.findOne({_id: request.decodedTokenData.userId})
        .exec()
        .then(user=>{
          const result = user.reports.find( ({ asset_report_id }) => asset_report_id === assetID );
          console.log('IN FIND',result);
        })
        .catch(err=>console.log(err))

Now i do get the result which is great and i can delete but isn't there a method to do it with mongoose directly? More alongthe lines of plain mongo version of :

db.removeObject.update( {'_id':ObjectId("5c6ea036a0c51185aefbd14f")},
 {$pull:{"reports":{"asset_report_id":234}}},false,true);
4
  • Can you try: {$pull:{"report":{"asset_report_id":234}}} ? Commented May 8, 2020 at 1:23
  • like this User.update({_id:request.decodedTokenData.userId},{$pull:{"reports":{"asset_report_id":234}}}); correct me in the syntax if its wrong thanks Commented May 8, 2020 at 1:26
  • Yes, but change reports -> report as your sample data's array doesn't end with "s" Commented May 8, 2020 at 1:27
  • 1
    this worked thankyou! although it should use updateOne update is deprecated :) you can answer this below as well i'll accept it since you helped me out. Commented May 8, 2020 at 1:31

1 Answer 1

1

So the correct solution is:

await User.updateOne( {'_id':ObjectId("5c6ea036a0c51185aefbd14f")},
   {$pull:{"report":{"asset_report_id":234}}},false,true)

since the data model contains "report" array

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.