findOneAndUpdate Mongoose函数中的string字面问题

类似于这个问题https://stackoverflow.com/questions/11183480/how-to-set-key-by-var-in-mongoose-node-js# =我无法获取findOneAndUpdate函数中的字段variables。 它把它当作文字领域。 我试图实现他们的解决scheme,但没有奏效。 我没有得到一个错误,它只是没有更新任何东西。

var cat = new Cat(); var field = (req.body[1].type); Cat.findOneAndUpdate({ 'sid': req.sessionID }, {$push: {field: req.body[0]}}, {'upsert': true, 'new': true}, function (err, data){ 

您需要使用括号[]表示法来将对象属性的“键”设置为来自variables的值:

 var cat = new Cat(); // Just use it in the below assignment instead //var field = (req.body[1].type); var update = { "$push": { } }; update.$push[req.body[1].type] = req.body[0]; Cat.findOneAndUpdate( { 'sid': req.sessionID }, update, // and reference in here {'upsert': true, 'new': true}, function (err, data){ 

这就是如何在JavaScript中dynamic分配一个键。