node.js - 为什么我无法替换查询更新参数 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}`)
}
})
}
解决方案
尝试使用计算属性键(请注意,这在旧 JS 版本中不起作用)来实现动态属性:
User.findOneAndUpdate({ _id: id }, { $set: { [valToUpdate]: newVal } }, (err, res) => {
或者,使用括号表示法:
const updateObject = {}
updateObject[valToUpdate] = newVal
User.findOneAndUpdate(..., {$set: updateObject},...)
推荐阅读
- angular - 使用 ASYNC 管道和返回的 Observable<{}> 更新 UI
- python - 如何找到两个列表的共同元素?
- angular - Angular Observable 发出与订阅者一样多的事件
- javascript - 如何在 Polymer 3 中使用 Firebase 身份验证?
- javascript - 如何等待带有承诺的可观察对象的每个值
- php - 警告:mysqli::__construct(): (HY000/2002): No such file or directory in
- javascript - 将照片保存在本地存储中并在另一个页面上显示
- powershell - 第一个参数完成后,如何在一个 foreach 循环中循环两个参数?
- mysql - 在 Docker/RDS 中的“加载数据本地 infile”期间获取“在查询期间丢失与 MySQL 服务器的连接”
- android - 如何在每 n 秒内使用 Android 应用程序自动拍摄照片