Search code examples
javascriptnode.jsmongodbexpressmongoskin

What's keyword about repeat $addtoset in mongodb by mongoskin ( I read english a little)


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] }

  }

Solution

  • 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.