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

8nuwlpux  于 2023-08-06  发布在  Go
关注(0)|答案(9)|浏览(147)

我的模型文档中有一个数组。我想根据我提供的键删除该数组中的元素,然后更新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();
        });
    });
};

字符串
到目前为止,它找到了文档,但删除或保存工作。

mnowg1ta

mnowg1ta1#

您也可以直接在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}],
    },
});


(you也可以对多个文档使用updateMany)
http://docs.mongodb.org/manual/reference/operator/update/pullAll/

cdmah0mi

cdmah0mi2#

检查的答案确实有效,但在MongooseJS最新的官方版本中,您应该使用pull

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

字符串
https://mongoosejs.com/docs/api.html#mongoosearray_MongooseArray-pull
我也在查。

请看丹尼尔的回答,以获得正确答案。好多了

u91tlkcl

u91tlkcl3#

上面的答案显示了如何删除数组,这里是如何从数组中提取对象。
参考: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.
)

字符串

ldioqlga

ldioqlga4#

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

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

字符串

zy1mlcev

zy1mlcev5#

这对我很有效,真的很有帮助。

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

字符串
我有一个模型的名称是SubCategory,我想从这个类别数组中删除优惠券。我有一个类别数组,所以我使用了arrOfSubCategory。因此,我在$in操作符的帮助下,使用map函数从这个数组中获取每个对象数组。

eivnm1vs

eivnm1vs6#

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

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

cu6pst1q

cu6pst1q7#

我在我的项目中使用了这种格式,并且很有效

router.delete('/dashboard/participant/:id', async (req, res, next) => {
    try {
        const participant = await Participant.findByIdAndDelete({ _id: req.params.id });
        // { $pull: { templates: { _id: templateid } } },
        const event = await Event.findOneAndUpdate({ participants: participant._id }, { $pull: { participants: participant._id } }, { new: true });
        res.status(200).json({ request: 'Deleted', participant, event });
    } catch (error) {
        res.json(error)
    }
});

字符串

9rbhqvlz

9rbhqvlz8#

Favorite.update({ cn: req.params.name }, { "$pull": { "favorites": { "_id": favoriteId } }}, { safe: true, multi:true }, function(err, obj) {
    //do something smart
});

字符串

kmbjn2e3

kmbjn2e39#

这是一个使用Mongoose的TypeScript示例。

// Each company has COI
// COI looks like { buildingId: string, name: string, file: string }
// Company is an Entity Company looks like { companyId: string, cois: COI[] }

function deleteCOI(companyId: string, buildingId: string) {
  const company = await Companies.findOneAndUpdate(
    { companyId },
    { $pull: { cois: { buildingId: buildingId } } }
  );
  return company;
}

字符串

相关问题