1

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

2 Answers 2

1

Look into the $pull operator

collection.movies.pull(req.body);
Sign up to request clarification or add additional context in comments.

Comments

0

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);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.