Home > OS >  Mongoose $pull method not working in my node.js application
Mongoose $pull method not working in my node.js application

Time:08-27

I have a MERN stack application and I am learning while building a little bit of a complex blog application. So far, everything has gone well. Here is what I want to do. An admin has the permission to delete single users, or all users or selected users. I am writing the logic for selected users. So, from the frontend, the admin selects the users he would like to delete. The backend receives the ids of the selected users that came from the frontend. It is an array. So, the admin could select 10 users, etc.

I have a Post model where users' posts are stored. This post model has an object value called postLikes which is an array of ids of the users who liked that particular post. Now, when the admin wants to delete some users, I also want everything about those users deleted including the likes. For example, if user A and user B were selected by the admin for deletion, and User A has already liked a post called Post B. But user B liked another post called Post F, their ids will be stored in the respective Post model, inside postLikesarray values. I want to also remove their ids from any post they already liked before deleting them.

The selected ids came in as array. I searched for all Post models and filtered it to return posts with Likes. Here is the code:

 const posts = await Post.find();

 const filteredPost = posts.filter((singleFilter) => singleFilter.postLikes.length !== 0);
 const {selectedIds} = req.body;// contains array of selected posts coming from frontend

 for(i = 0; i < filteredPost.length; i  ){
        for(h = 0; h < selectedIds.length; h  ){
            if(filteredPost[i].postLikes == selectedIds[h]){
                
               const updatedPost = await Post.findByIdAndUpdate(filteredPost[i]._id, { $pull: {postLikes: selectedIds[h] } })
              console.log(updatedPost)
            }
          
        }

    }

This code just runs without actually deleting the selected users' ids from their respective Post model postLikes array. I have also tried mongoose updateMany, didnt work.

Kindly help me out. Thanks

CodePudding user response:

you could do something like this:


const posts = await Post.find();

const filteredPost = posts.filter((singleFilter) => singleFilter.postLikes.length !== 0);
const {selectedIds} = req.body;// contains array of selected posts coming from frontend


filteredPost.foreach(async post=>{
    /*
lets say your "postLikes" array looks like this: 
[{_id:"0",liked_by_user_with_id:"123"},
{_id:"1",liked_by_user_with_id:"456"},
{_id:"2",liked_by_user_with_id:"789"}]
   */ 

  
    post.postLikes.filter(like=>!selectedIds.includes(like.liked_by_user_with_id))
    await post.save();


});

CodePudding user response:

You could let the MongoDB server do all the work with something like this. I suppose my array of ObjectIds used below would be replaced by req.body in your case, and you would use updateMany and not need {"multi": true}.

db.Post.update({
  "postLikes": {
    "$in": [
      ObjectId("6309548f820a879df1436862"),
      ObjectId("6309548f820a879df1436867")
    ]
  }
},
{
  "$pullAll": {
    "postLikes": [
      ObjectId("6309548f820a879df1436862"),
      ObjectId("6309548f820a879df1436867")
    ]
  }
},
{"multi": true}
)

Try it on mongoplayground.net.

I'm not a "Mongooser", but perhaps it would look like:

const res = await Post.updateMany({"postLikes": {"$in": req.body }}, {"$pullAll": {"postLikes": req.body}});
  • Related