Home > Back-end >  How to remove a certain position from an array of objects that matches a value in Mongoose?
How to remove a certain position from an array of objects that matches a value in Mongoose?

Time:01-13

Is the first time I am working with backend (Mongoose, express, nodeJs). I have a collection of users in MongoDB. I am sending the favoriteId from frontend and getting it in the backend. I want to delete the position of the array that matches with the favorite Id I am passing to the function. I have tried several ways to remove the favorite using the $pull operator and the favoriteId but none work. So I don't know how to do it.

I would appreciate if someone could help me.

This is structure in MongoDB:

    _id: new ObjectId("63"),
    username: 'test1',
    email: '[email protected]',
    favorites: [
      {
        id: '25',
        version: 'version3',
        team: 'team1',
      },
      {
        id: '27',
        version: 'version2',
        team: 'team4',
      }```

This is my controller function:

```export const removeFavorite = async (req, res) => {
    //Here I have the user Id 63
    const userId = req.params.userId;

    //here I have the favorite Id I Want to remove : 25
    const favoriteId = req.body.params.id;

    // Here I select the user in the collection 
    const deleteFavorite = await User.findOne({ _id: userId });

    // Here I want to remove the favorite that matches with favoriteId (25)

    res.status(200).json('ok');
};```



CodePudding user response:

try this

User.update({ _id: userId }, { $pull: { 'favorites': { 'id': favoriteId } } });

  • Related