简体   繁体   中英

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

查看 $pull 运算符

collection.movies.pull(req.body);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM