In this code that uses the mongodb-native driver I'd like to increase the value of the field which I 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 variable selected works as expected and finds the correct id.
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 should I do it so that instead of the word 'variable' there will be the contents of the variable?
In this code that uses the mongodb-native driver I'd like to increase the value of the field which I 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 variable selected works as expected and finds the correct id.
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 should I do it so that instead of the word 'variable' there will be the contents of the variable?
Share Improve this question edited Mar 10, 2014 at 6:49 Dan Dascalescu 152k64 gold badges332 silver badges419 bronze badges asked Jun 21, 2012 at 8:02 Timo AlbertTimo Albert 6551 gold badge6 silver badges17 bronze badges1 Answer
Reset to default 13Set the key of another variable to its value and pass that as an object. Note of action:
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} }