0

Hey I'm trying to remove an object from mongodb array i think my code is right but i don't know why it is not removing the object from array

This is a document in mongodb collection i want to remove the element from array likedsongs

{
    "_id" : ObjectId("611fc7284bf68143086544f9"),
    "artistrating" : [],
    "username" : "afaqfiaz2311@gmail.com",
    "name" : "Afaq Fiaz",
    "usertype" : "User",
    "picid" : "artistpic-1629472550162.jpeg",
    "songs" : [],
    "__v" : 0,
    "likedsongs" : [ 
        {
            "likes" : [ 
                "611bf34e6ea7023018fcff2a", 
                "611fc7284bf68143086544f9"
            ],
            "_id" : ObjectId("611d28e97782820fc039dd85"),
            "songname" : "Koi Naa",
            "songartistname" : "Khaq",
            "songartworkid" : "artworkid-1629300962014.jpg",
            "songaudioid" : "audioid-1629300962038.mp3",
            "songcomments" : [],
            "__v" : 0
        }
    ]
}

The Query is :

User.findOneAndUpdate(
  { _id: "611fc7284bf68143086544f9" },
  { $pull: { likedsongs: { _id: "611d28e97782820fc039dd85" } } },
  { new: true }, function(err){
    if(err){
      console.log(err);
    }else{
      console.log("Removed");
    }
  }
)

It is showing "Removed" in the console also there is no error but the object is not actually removing from the collection its still there Please Help

  • Does this answer your question? [Node.js Mongoose.js string to ObjectId function](https://stackoverflow.com/questions/6578178/node-js-mongoose-js-string-to-objectid-function) – Montgomery Watts Aug 24 '21 at 02:13

1 Answers1

0

you should use

elemMatch

User.findOneAndUpdate(
  { _id: "611fc7284bf68143086544f9" },
  { $pull: { likedsongs: {$elemMatch:{ _id: "611d28e97782820fc039dd85" }} } },
  { new: true }, function(err){
    if(err){
      console.log(err);
    }else{
      console.log("Removed");
    }
  }
)
mohammad Naimi
  • 2,259
  • 1
  • 5
  • 15