0

How can I update ALL documents in a collection where an attributes value needs to be different (a unique number) for each document?

Below is my current code. This actually seems to update (I don't get an error) but the values in the db are not being updated.

Model.find({}, function (err, docs) {

    if (err) {

        console.log(err);

    };



if(docs && docs.length > 0){


    for(var i=0; i<docs.length; i++){

    //SET NEW VALUE FOR EACH DOC - VALUE MUST BE UNIQUE TO EACH DOC
        docs[i].code = generateRandomCode();    

    }


    // PASS IN ARRAY OF UPDATED DOCS TO BE SAVED
    Model.update(docs, function (err, docs) {
        if (err) {
            console.log(err);
        }

        if(!err){   
            req.updatedSuccessfully = true;
        }

        return next();



    });


}
else{

    return next();

}


});

Before this I was trying to do something like this:

Model.update({}, { code: generateRandomCode() }, { multi: true }, function (err,      numberAffected, raw) {
  if (err) return handleError(err);
  console.log('The number of updated documents was %d', numberAffected);
  console.log('The raw response from Mongo was ', raw);
});

The problem with this is that generateRandomCode() is only called once but I need to create a different code for each document. So neither of these example work.

Paulie
  • 1,567
  • 4
  • 16
  • 21
  • I wonder if this is an async issue? If you console within the `!err` condition, and right before the `return next()`, do they happen in the correct order? – bencripps Sep 09 '14 at 18:33
  • No its fine. The issue is more that I don't think you can pass an array of docs with Model.update. You query your documents and set any values you want within the update function and set multi to true. But you can't set unique values for the docs you are updating. I have added additional code to show this. – Paulie Sep 09 '14 at 18:56

1 Answers1

0

Instead of trying model.update(), can you try to simply save the documents?

See answer to this question on this url: Update model with Mongoose, Express, NodeJS

Community
  • 1
  • 1