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. 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.