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

标签 node.js mongoose

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

这是我的尝试:

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

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

最佳答案

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

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

从数组中移除对象

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

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

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

关于node.js - Mongoose 删除文档中的数组元素并保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14763721/

相关文章:

Node.js 400 错误请求

node.js - mongoose - 为什么 findOne 返回 mongoose Model 对象,但 find 却没有?

javascript - Mongoose 按数组条目 ($in) 进行搜索的行为与 MongoDB Atlas 不一致

javascript - 全局安装的 NodeJS npm 模块不会使用 Node 执行 main/bin JavaScript 文件

node.js - 我们如何获取ejs页面的html字符串并将其值存储在ExpressJS中的字符串中?

node.js - 将子进程的输出保存在 NodeJS 父进程的变量中

node.js - mongoose.findOneAndUpdate() 更改保存在我的 Express 应用程序中的值

javascript - 如何使用node.jsexpress渲染多个html页面?

node.js - 预期 'property' 是字符串类型,而不是找到类型对象 - Dynamoose

mongoose - 如何使用 Mongoose 设置 'cursorTimeoutMillis'