MongoDB 中的 UpdateMany 使用 $inc 运行两次

2024-01-11

感谢我在上一个问题中得到的帮助(使用文档中的值更新许多 mongodb 文档 https://stackoverflow.com/questions/63530102/updatemany-mongodb-documents-with-value-from-document),我已经了解了如何使用 updateMany 进行增量。我写了以下代码:

ageAllCameraPriorities = async (req, res) => {
    await Camera.updateMany({ enabled: true }, { $inc: { processingPriority: 1 } }, (err, dbResp) => {
        if (err) {
            return res.status(400).json({ success: false, error: "Status 400, unable to age camera priorities" + err })
        }
        if (!dbResp.n) {
            return res
                .status(404)
                .json({ success: false, error: `No enabled cameras found to age` })
        }
        return res.status(200).json({ success: true, data: dbResp })
    })

        .catch(err => console.log(err))
}

这段代码的目的是运行一个 mongoDB 数据库,如下所示:

[{
    _id: 'ad07f',
    enabled: true,
    priority: 1,
    more: "more data"
},{
    _id: '9da0f',
    enabled: false,
    priority: 6,
    more: "more data"
},{
    _id: '35fas',
    enabled: true,
    priority: 3,
    more: "more data"
},{
    _id: '5f3ax',
    enabled: true,
    priority: 11,
    more: "more data"
}]

...并将每个启用文档的“优先级”字段增加 1。

然而,上面的代码将值增加了 2。

此外,如果我更改为$inc: { priority: 3 }该值增加了 6。在我看来,某件事可能会运行两次。但我直接用邮递员到达端点,上面的代码是我的函数的全部。第二个增量从哪里来?

EDIT:
很明显,第二次运行发生在这条线上:return res.status(200).json({ success: true, data: dbResp })因为我可以取出除该行之外的所有内容,并且它会增加 2。如果我删除该行,它只会增加 1。(但 API 端点永远不会返回任何内容......所以这不好)


根据对原始问题的评论,我能够通过删除来解决这个问题.catchawait.

ageAllCameraPriorities = async (req, res) => {
    Camera.updateMany(  { enabled: true },
        { $inc: { processingPriority: req.params.amount } },
        {},
        (err, dbResp) => {
        if (err) {
            return res
                .status(400)
                .json({ success: false, error: "Status 400, unable to age camera priorities" + err })
        }
        if (!dbResp.n) {
            return res
                .status(404)
                .json({ success: false, error:'No enabled cameras found to age' })
        }
            return res
                .status(200)
                .json({ success: true, data: dbResp })
    })
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

MongoDB 中的 UpdateMany 使用 $inc 运行两次 的相关文章

随机推荐