繁体   English   中英

Mongoose 从文档数组中查找和删除对象

[英]Mongoose FInd and remove object from array of a document

我有一个文件“收藏”:

{
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},}

我需要从电影 [] 中查找并删除特定项目。 这是我目前拥有的,它不起作用。

req.body 是一个通过 POST 请求的数据传递的对象,并且具有能够匹配 movies[] 数组中的一个所需的所有信息

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

它目前所做的只是弹出数组中的前面对象,但我需要它来删除数组中等于 req.body 的对象

查看 $pull 运算符

collection.movies.pull(req.body);

您可以使用$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);
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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