首页 > 解决方案 > 为什么我无法替换查询更新参数 findOneAndUpdate() / updateOne() 中的变量值?

问题描述

我正在尝试一种方法来更新 MongoDB 中的不同参数,使用 mongoose。但是由于某种原因不能在变量中传递更新字段。有什么技巧可以做到这一点吗?

const updateCurrentUser = async (req, res, next) => {
    const { token, valToUpdate, newVal } = req.body;
    const id = jwt.verify(token, secretWord).userId;
    User.findOneAndUpdate({ _id: id }, { $set: { valToUpdate: newVal } }, (err, res) => {
        if (err) {
            console.log(`errror: ${err}`)
        }
        else {
            console.log(`resss: ${res}`)
        }
    })

}

标签: node.jsmongoose

解决方案


尝试使用计算属性键(请注意,这在旧 JS 版本中不起作用)来实现动态属性:

    User.findOneAndUpdate({ _id: id }, { $set: { [valToUpdate]: newVal } }, (err, res) => {

或者,使用括号表示法:

const updateObject = {}
updateObject[valToUpdate] = newVal
User.findOneAndUpdate(..., {$set: updateObject},...)

推荐阅读