Mongoose删除文件中的数组元素并保存

occ*_*asl 51 mongoose node.js

我的模型文档中有一个数组.我想根据我提供的密钥删除该数组中的元素,然后更新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();
        });
    });
};
Run Code Online (Sandbox Code Playgroud)

到目前为止,它找到了文档,但删除或保存工作.

Dan*_*nce 94

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

Favorite.update( {cn: req.params.name}, { $pullAll: {uid: [req.params.deleteUid] } } )
Run Code Online (Sandbox Code Playgroud)

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

  • 我没有得到如何从收藏夹数组(子数组而不是文档)中删除项目而不引用名称收藏夹 (3认同)
  • @Dominic 现在添加了“收藏夹”。我不敢相信这件事已经被忽视了 6 年多 (2认同)

Jas*_*ing 43

已检查的答案确实有效,但最近在MongooseJS中正式使用,你应该使用pull.

doc.subdocs.push({ _id: 4815162342 }) // added
doc.subdocs.pull({ _id: 4815162342 }) // removed
Run Code Online (Sandbox Code Playgroud)

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

我也只是看着那个.

请参阅Daniel的答案以获得正确的答案.好多了.


Roe*_*den 5

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

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);
    });
};
Run Code Online (Sandbox Code Playgroud)

  • 如果你试图同时删除2个东西,它们都可以获得数组,然后更改它,第一个保存的更改将被第二个覆盖.我宁愿像这样去http://stackoverflow.com/questions/16959099/how-to-remove-array-element-in-mongodb. (3认同)

小智 5

上面的答案显示了如何删除数组,以及如何从数组中拉出对象。

参考: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.
)
Run Code Online (Sandbox Code Playgroud)