简体   繁体   English

findOneAndUpdate Mongoose 函数中的字符串文字问题

[英]String Literal Issue in findOneAndUpdate Mongoose Function

Similar to this issue https://stackoverflow.com/questions/11183480/how-to-set-key-by-var-in-mongoose-node-js# = I cannot get the field variable in the findOneAndUpdate function.与此问题类似https://stackoverflow.com/questions/11183480/how-to-set-key-by-var-in-mongoose-node-js# =我无法在findOneAndUpdate函数中获取字段变量。 It takes it as literal field.它将它作为文字字段。 I tried to implement their solution but it did not work.我试图实施他们的解决方案,但没有奏效。 I didn't get an error it just didn't update anything.我没有收到错误,只是没有更新任何内容。

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){

You need to use the bracket [] notation in order to set the "key" of an object property to a value from a variable:您需要使用方括号[]符号将对象属性的“键”设置为变量中的值:

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){

That's how to dynamically assign a key in JavaScript.这就是在 JavaScript 中动态分配键的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM