Mongoose 删除文档中的数组元素并保存 [英] Mongoose delete array element in document and save

查看:26
本文介绍了Mongoose 删除文档中的数组元素并保存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

这是我的尝试:

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.

推荐答案

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

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

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

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

(you can also use updateMany for multiple documents)

http://docs.mongodb.org/manual/reference/运算符/更新/pullAll/

这篇关于Mongoose 删除文档中的数组元素并保存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆