How to use a variable as a field name in mongodb-native findAndModify?

In this code, which uses the mongodb native driver, I would like to increase the value of the field, which I will specify in a separate variable. The problem is that the field name in the $ inc clause will be "variable" in this case, not the contents of the variable. In the query part, the selected variable works as expected and finds the correct identifier.

var selected = 'id_of_the_selected_one'; var variable = 'some_string'; collection.findAndModify( {_id : selected}, {}, {$inc : {variable : 1}}, {new : true, upsert : true}, function(err, autoincrement) { /* ... */ } ); 

How can I do this so that instead of the word "variable" is the contents of the variable?

+6
source share
1 answer

Set the key of another variable to a value and pass it as an object. Action Note:

 var selected = 'id_of_the_selected_one'; var variable = 'some_string'; var action = {}; action[variable] = 1; // the value collection.findAndModify( {_id : selected}, {}, {$inc : action}, {new : true, upsert : true}, function(err, autoincrement) { /* ... */ } ); // Same as {$inc: {'some_string': 1} } 
+13
source

Source: https://habr.com/ru/post/918639/


All Articles