如何将字段名称传递到Mongoose的update()方法?

我想更新dataToChange对象中包含的每个字段,但由于某种原因,我不能将密钥名称传递到update(),我的意思是该方法不会从外部拿起它,它正在数据库的对象中寻找“key”字段。 我该怎么做? 我试图使用${key} ,但它被认为是一个错误。

 changeUserInfoFashion = function (id, dataToChange, res, callback) { //var id = id; _.forIn(dataToChange, function (value, key) { key.toString(); console.log('I AM GOING TO UPDATE ' + key + " WITH " + value); User.update( {"_id": id}, //Here I need to pass key --> {key: value}, function (err, results) { console.log(results); if (err) { return callback(); } return res.json({success: true, msg: key + ' changed.'}).status(200); }); }); }; 

dataToChange的例子是

 { name: 'Baby', age: 32 } 

无需迭代对象并更新每个字段,您可以使用$set运算符,如下所示:

 changeUserInfoFashion = function (id, dataToChange, res, callback) { User.update( { "_id": id }, { "$set": dataToChange }, function (err, results) { console.log(results); if (err) { return callback(); } return res.json({ success: true, msg: JSON.stringify(dataToChange) + ' changed.' }).status(200); } ); }; 

这是行不通的。 创build一个空对象并为其分配键值:

 _.forIn(dataToChange, function (value, key) { key.toString(); console.log('I AM GOING TO UPDATE ' + key + " WITH " + value); var updateData = {}; updateData[key] = value; User.update( {"_id": id}, //Here I need to pass key --> updateData, function (err, results) { console.log(results); if (err) { return callback(); } return res.json({success: true, msg: key + ' changed.'}).status(200); }); }); 
 changeUserInfoFashion = function (id, dataToChange, res, callback) { //var id = id; User.update( {"_id": id}, dataToChange, function (err, results) { console.log(results); if (err) { return callback(); } return res.json({success: true, msg: key + ' changed.'}).status(200); }); };