-1

Sorry, I can't find answer and I can't read english.

What's keyword can find answer about the following example code ?

for(var value in row){
db.collection('testdb').update({_id:'id'},{$addToSet:value},                                                                            
   { upsert: true },function(err){}
)
value.empty();

}

I don't know why my code can't work

testdb: { "_id" : "id", "v" : [v1], "p" : [ p1] }

after repeat update

{ "_id" : "id", "v" : [v1,p2], "p" : [ p1,p2] }

but should be

{ "_id" : "id", "v" : [v1,v2], "p" : [ p1,p2] }   

to Neil Lunn

row count = 2 ;
row[0] = { "v" : [v2] }
row[1] = { "p" : [p2] }

to Farid Nouri Neshat

app.post('index',function(req,res){

    var doc =[];
    var d ={};
    var e ={}
    for(var value in req.body){            
        d[value]=doc;                
        e['$each']=doc;
        d[value]=e;               
        db.collection('testdb').update({_id:req.body.field},{$addToSet:d},                                       
           { upsert: true },function(err){})                                            
        doc=[];//clear doc
        d={};//clear d
        }
    }
 // req.body.count = 2
 // req.body[0] = { "v" : [v2] }
 // req.body[1] = { "p" : [p2] }

  }
user2468652
  • 117
  • 1
  • 9
  • What are you passing in as `value`? You have two arrays (sets) in here and you are not showing us that part of your statement. – Neil Lunn May 19 '14 at 03:44
  • 1
    http://docs.mongodb.org/manual/reference/operator/update/each/#up._S_each – DhruvPathak May 19 '14 at 05:21
  • There's not enough information in here. If the row is `[{ v: [v2], p : [p2] }]` then nothing is wrong here. Share more code. Post a minimal example that can be run on our computers locally showing the problem. – Farid Nouri Neshat May 19 '14 at 08:49

1 Answers1

0

I think the code you posted doesn't replicate the problem. But judging from the fact that both p and v arrays, got the last value, It looks like, that you are running update method in a callback in the for loop, so when the update method is run, the key is already changed to the last key. You can read more about the problem in this question: JavaScript closure inside loops – simple practical example

What I suggest you to try is to instead of using for(var value in req.body) { change that using Object.keys:

Object.keys(req.body).forEach(function (value) {
    // Do whatever you do inside the loop in here.
});

This will capture value argument and it won't change on the next iterations. I have explained this in a similar problem.

Community
  • 1
  • 1
Farid Nouri Neshat
  • 29,438
  • 6
  • 74
  • 115