首页 > 解决方案 > 如何使用基于唯一id的节点更新mongodb中的多个文档

问题描述

如何在 mongoose 中更新多个文档,我知道如何更新与其他文档匹配的多个文档,但我希望使用 id 更新多个文档。

我尝试了很多方法,这里是其中之一。

更新

var myid = req.params.noteId

   Note.updateMany({ _id:{ $in:ObjectID(myid) } }, {

       lname: req.body.lname || "Untitled Note",
       age: req.body.age
   }, { new: true })
       .then(note => {
           if (!note) {
               return res.status(404).send({
                   message: "Note not found with id " + req.params.noteId
               });
           }
           res.send(note);
       })

还有一件事我如何将多个 Id 作为参数传递以更新邮递员测试仪中的多个文档。

标签: node.jsexpressmongoose

解决方案


mongoose.Types.ObjectId.isValid将返回布尔值。检查这个https://github.com/mongodb/js-bson/blob/f7efecc04240525931402116f881b5984af800c4/lib/bson/objectid.js#L247

如果您想更新多个 id 以在 req.body 中传递这些 id

多次使用 $in 否则直接通过。

var myid = req.params.noteId;

if (mongoose.Types.ObjectId.isValid(myid)) {
    Note.update({
            _id: mongoose.Types.ObjectId(myid)
           // _id: {$in: req.body.somekey_array.map(id => mongoose.Types.ObjectId(id ))} //multiple
        }, {

            lname: req.body.lname || "Untitled Note",
            age: req.body.age
        }, {
            multi: true //multiple
        })
        .then(note => {
            console.log('----qqqqq--', note)
            if (!note) {
                return res.status(404).send({
                    message: "Note not found with id " + req.params.noteId
                });
            }
            res.json(note);
        });
} else {
    res.status(400).json({
        msg: 'id not correct'
    });
}

推荐阅读