2

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!

JMax
26.7k12 gold badges74 silver badges89 bronze badges
asked Apr 20, 2012 at 9:29

1 Answer 1

4

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); });
answered Apr 20, 2012 at 9:53
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.