I have an array of numbers :
readersNum : {type: [Number], default: []},
I would like to increase the value placed in the indexVariable by 1.
this works :
Posts.update({"readerID":readerID},{$inc:{"readersNum.0":1}},{upsert:true,safe:true},
function(err){
console.log(err);
});
but the problem is i the value is not in a specific(constant) index it is a variable.. assuming the index variable is indexVariable
and not 0, how should i increase it?
I tried also this :
Posts.findOne({"readerID":readerID },['readersNum'],function(err, readerID){
readerID.readersNum[indexVariable] = readerID.readersNum[indexVariable]+1;
try {
Posts.save(readerID,function(err) {
if (err) {
console.log("ERROR while saving reader num: " + err);
}
else {
console.log('saved reader num successfully');
}
});
}
catch(e){
console.log("ERROR while saving reader num: " + e);
}
});
executing the code above prints the changed value in the console and "saved reader num successfully" but the value in the database stays the same! I would really appreciate it if someone could tell me what am i doing wrong. Thank you!
Assuming that you know the index you could do this:
var update = {};
update['readersNum.' + index] = 1; // update now has property like `readersNum.3`
Posts.update({"readerID":readerID},{$inc: update},{upsert:true,safe:true}, function(err){ console.log(err); });