node.js Mongoose 删除文档中的数组元素并保存

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14763721/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 17:07:01  来源:igfitidea点击:

Mongoose delete array element in document and save

node.jsmongoose

提问by occasl

I have an array in my model document. I would like to delete elements in that array based on a key I provide and then update MongoDB. Is this possible?

我的模型文档中有一个数组。我想根据我提供的键删除该数组中的元素,然后更新 MongoDB。这可能吗?

Here's my attempt:

这是我的尝试:

var mongoose = require('mongoose'),
    Schema = mongoose.Schema;

var favorite = new Schema({
    cn: String,
    favorites: Array
});

module.exports = mongoose.model('Favorite', favorite, 'favorite');

exports.deleteFavorite = function (req, res, next) {
    if (req.params.callback !== null) {
        res.contentType = 'application/javascript';
    }
    Favorite.find({cn: req.params.name}, function (error, docs) {
        var records = {'records': docs};
        if (error) {
            process.stderr.write(error);
        }
        docs[0]._doc.favorites.remove({uid: req.params.deleteUid});

        Favorite.save(function (error, docs) {
            var records = {'records': docs};
            if (error) {
                process.stderr.write(error);
            }
            res.send(records);

            return next();
        });
    });
};

So far it finds the document but the remove nor save works.

到目前为止,它找到了文档,但删除或保存都有效。

回答by Daniel Flippance

You can also do the update directly in MongoDB without having to load the document and modify it using code. Use the $pullor $pullAlloperators to remove the item from the array :

您也可以直接在 MongoDB 中进行更新,而无需加载文档并使用代码对其进行修改。使用$pullor$pullAll运算符从数组中删除项目:

Favorite.updateOne( {cn: req.params.name}, { $pullAll: {uid: [req.params.deleteUid] } } )

(you can also use updateMany for multiple documents)

(您也可以对多个文档使用 updateMany)

http://docs.mongodb.org/manual/reference/operator/update/pullAll/

http://docs.mongodb.org/manual/reference/operator/update/pullAll/

回答by Jason Sebring

The checked answer does work but officially in MongooseJS latest, you should use pull.

检查的答案确实有效,但在最新的 MongooseJS 中正式发布,您应该使用pull

doc.subdocs.push({ _id: 4815162342 }) // added
doc.subdocs.pull({ _id: 4815162342 }) // removed

https://mongoosejs.com/docs/api.html#mongoosearray_MongooseArray-pull

https://mongoosejs.com/docs/api.html#mongoosearray_MongooseArray-pull

I was just looking that up too.

我也是刚查的

See Daniel's answer for the correct answer. Much better.

有关正确答案,请参阅 Daniel 的答案。好多了。

回答by Mike Musni

Answers above are shown how to remove an array and here is how to pull an object from an array.

上面的答案显示了如何删除数组,这里是如何从数组中提取对象。

Reference: https://docs.mongodb.com/manual/reference/operator/update/pull/

参考:https: //docs.mongodb.com/manual/reference/operator/update/pull/

db.survey.update( // select your doc in moongo
    { }, // your query, usually match by _id
    { $pull: { results: { $elemMatch: { score: 8 , item: "B" } } } }, // item(s) to match from array you want to pull/remove
    { multi: true } // set this to true if you want to remove multiple elements.
)

回答by Hozuki

Since favorites is an array, you just need to splice it off and save the document.

由于收藏夹是一个数组,您只需要将其拼接并保存文档即可。

var mongoose = require('mongoose'),
    Schema = mongoose.Schema;

var favorite = new Schema({
    cn: String,
    favorites: Array
});

module.exports = mongoose.model('Favorite', favorite);

exports.deleteFavorite = function (req, res, next) {
    if (req.params.callback !== null) {
        res.contentType = 'application/javascript';
    }
    // Changed to findOne instead of find to get a single document with the favorites.
    Favorite.findOne({cn: req.params.name}, function (error, doc) {
        if (error) {
            res.send(null, 500);
        } else if (doc) {
            var records = {'records': doc};
            // find the delete uid in the favorites array
            var idx = doc.favorites ? doc.favorites.indexOf(req.params.deleteUid) : -1;
            // is it valid?
            if (idx !== -1) {
                // remove it from the array.
                doc.favorites.splice(idx, 1);
                // save the doc
                doc.save(function(error) {
                    if (error) {
                        console.log(error);
                        res.send(null, 500);
                    } else {
                        // send the records
                        res.send(records);
                    }
                });
                // stop here, otherwise 404
                return;
            }
        }
        // send 404 not found
        res.send(null, 404);
    });
};

回答by coder

This is working for me and really very helpful.

这对我有用,真的非常有帮助。

SubCategory.update({ _id: { $in:
        arrOfSubCategory.map(function (obj) {
            return mongoose.Types.ObjectId(obj);
        })
    } },
    {
        $pull: {
            coupon: couponId,
        }
    }, { multi: true }, function (err, numberAffected) {
        if(err) {
            return callback({
                error:err
            })
        }
    })
});

I have a model which name is SubCategoryand I want to remove Coupon from this category Array. I have an array of categories so I have used arrOfSubCategory. So I fetch each array of object from this array with map function with the help of $inoperator.

我有一个模型,它的名字是SubCategory,我想从这个类别数组中删除 Coupon。我有一系列类别,所以我使用了arrOfSubCategory. 所以我在$in运算符的帮助下使用 map 函数从这个数组中获取每个对象数组。

回答by crazy_phage

keywords = [1,2,3,4];
doc.array.pull(1) //this remove one item from a array
doc.array.pull(...keywords) // this remove multiple items in a array

if you want to use ...you should call 'use strict';at the top of your js file; :)

如果你想使用...你应该'use strict';在你的 js 文件的顶部调用;:)