类似本期https://stackoverflow.com/questions/11183480/how-to-set-key-by-var-in-mongoose-node-js#=我无法在 findOneAndUpdate 函数中获取字段变量。它将它作为文字字段。我尝试实现他们的解决方案,但没有成功。我没有收到错误,只是没有更新任何内容。
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){
最佳答案
您需要使用方括号[]
表示法才能将对象属性的“键”设置为变量中的值:
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 中动态分配键。
关于javascript - findOneAndUpdate Mongoose 函数中的字符串文字问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33489377/