5

Mongoose findOneAndUpdate callback with array of identifiers

 3 years ago
source link: https://www.codesd.com/item/mongoose-findoneandupdate-callback-with-array-of-identifiers.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Mongoose findOneAndUpdate callback with array of identifiers

advertisements

I am using findOneAndUpdate in a forEach loop to create/update multiple entries.

I would like it to return an array of all the object id's it has created or updated.

During the loop, I can see it adding data to the array, but one it leaves the loop, the array is empty.

Should the array not be populated?

here is my code.

var softwareArray = ["Software1","Software2","Software3"],
updatedArray = [];

softwareArray.forEach(function(software){
    Software.findOneAndUpdate(
        {
            Name: software
        },
        {
            Name: software
        },
        {upsert:true},
        function(err, rows){
            updatedArray.push(rows._id);
            console.log(updatedArray); //This has data in it....
        }
    );
});
console.log(updatedArray); //This has no data in it...

Edit: Updated with my working changes for Thiago

var softwareArray = ["Software1","Software2","Software3"],
updatedArray = [];

loopSoftware(softwareArray, function(updatedArray){
    console.log(updatedArray);
    //carry on....
}

function loopSoftware(input, cb){
    var returnData = [];

    var runLoop = function(software, done) {
        Software.findOneAndUpdate(
            {Name: software},
            {Name: software},
            {upsert:true},function(err, rows){
                returnData.push(rows._id);
                done()
            }
        );
    };

    var doneLoop = function(err) {

        cb(returnData);

    };

    async.forEachSeries(input, runLoop, doneLoop);
}


Of course this will happen - just like any other networking on Node, it's asynchronous!

This means that the callback you specified for your findOneAndUpdate operation have not run yet when it reaches the console.log(updatedArray); code.

Take a look at Q for working around this common problem.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK