Home > front end >  Deleting an item from a MongoDB document
Deleting an item from a MongoDB document

Time:01-06

I'm using Node.js. I got this document:

   {
   users: [ '614e000c826b2308ec49508d', '614e0021826b2308ec49508e' ],
   _id: 61d5fe6af420232658ffe131,
   name: 'Standard',
   __v: 0
   }

Which I assigned to a variale groupToEdit

I'm trying to remove one of the elements in the users array with this line:

    await groupToEdit.updateOne(
      { _id: '61d5fe6af420232658ffe131' },
      { $pull: { 'users': '614e000c826b2308ec49508d' } }
    )

But nothing is removed. What am I doing wrong?

CodePudding user response:

Use this style:

await yourCollection.updateOne({
  _id: mongoose.Types.ObjectId('61d5fe6af420232658ffe131')}, {
  $pull: { 'users': '614e000c826b2308ec49508d' }
});

Your problem is that mongoDB store _id as ObjectId and you are passing it as a string. Type of the id you pass is important.

  •  Tags:  
  • Related