timhc22
timhc22

Reputation: 7451

NodeJS and MongoDB update not working

I have this loop in a Node and Mongo application. console.log will output all the 'product' names correctly, however, rank is usually not set correctly in the database. Interestingly enough, if I put a debug breakpoint in the program and step through slowly, it works. Any idea if there is some sort of race condition taking place, and what the best solution for making this work would be?

async.each(sortedProductsArray, function (product, callback) {
    console.log(product.name);
    var query = {
        productNo: product.productNo
    };

    var index = sortedProductsArray.indexOf(product)+1;
    var update = {
        // give it a rank
        $set: { 'rank': index }
    };

    // main products array
    products.update(query, update, callback);
});

Upvotes: 0

Views: 188

Answers (1)

andrew.butkus
andrew.butkus

Reputation: 777

you should probably be using forEachOf and this will return the index as the second parameter, e.g.:

async.forEachOf(['a', 'b', 'c'], function () {console.log(arguments)});

{ '0': 'a', '1': 0, '2': [Function] } { '0': 'b', '1': 1, '2': [Function] } { '0': 'c', '1': 2, '2': [Function] }

and then you should be using this index rather than doing another search over your products collection

edit:

when you call products.update(query, update, callback); this affects the products array, and therefore may not be valid when you do your indexOf() (may not exist) which is why the rank sometimes isnt populated

Upvotes: 1

Related Questions