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?
MongoDB – FindAndModify() Method. The findAndModify() method modifies and return a single document that matches the given criteria. By default, this method returns a pre-modification document. To return the document with the modifications made on the update, use the new option and set its value to true.
Definition. The findAndModify command modifies and returns a single document. By default, the returned document does not include the modifications made on the update. To return the document with the modifications made on the update, use the new option.
A findAndModify operation on a document is atomic: if the find condition matches a document, the update is performed on that document. Concurrent queries and additional updates on that document are not affected until the current update is complete.
If new is true : the modified document if the query returns a match; the inserted document if upsert: true and no document matches the query; otherwise, null .
Set 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} }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With