JakePlatford
JakePlatford

Reputation: 134

Mongoose FInd and remove object from array of a document

I have a document 'Collection':

{
name: {type: String, required: true, default: "Untitled Collection"},
movies: [
        {  the_id: {type: String},
            movie_id: {type: String},
            tmdb_id: {type: String},
             original_title: {type: String},
              release_date: {type:Date}
        }],
author: {type: String},}

I need to find and remove a specific item from movies []. This is what I have currently, and it does not work.

req.body is an object passed through the data of a POST request and has all the information necessary to be able to match one in the movies[] array

 Collection.findOne({_id : req.params.id}, (err, collection) =>{
        if(err){res.status(400).json(err);}

        if(!collection)
        {
            res.status(404).json({message: 'No collection found'});
        }else{
            collection.movies.pop(req.body);
            collection.save();

            res.json(collection);
        }
    });

All it currently does is pop off the front object in the array, but I need it to remove the object in the array that is equal to req.body

Upvotes: 1

Views: 978

Answers (2)

Bertrand Martel
Bertrand Martel

Reputation: 45352

You can remove an item in an array with $pull

Collection.update({
    _id: req.params.id
}, {
    $pull: {
        'movies': req.body
    }
}, (err, collection) => {
    if (err) {
        res.status(400).json(err);
    }
    console.log(res);
    res.status(200);
});

Upvotes: 0

Jeff Justice
Jeff Justice

Reputation: 234

Look into the $pull operator

collection.movies.pull(req.body);

Upvotes: 1

Related Questions