Update an array of documents in Mongoose

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.

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