Cannot conduct multiple queries based on values within array?

Ad

Simply put, I want my user to be able to enter in a variety of SKUs and UPCs (comma delimited) in a search field in which I produce an array of search values and conduct an iterative process to return results/logic for each value (ie. 1 UPC can represent 3 SKUs, I would return the cheapest SKU for the UPC product searched).

  • Products with UPCs are found from Product.js.
  • Products with SKUs are found from vendorProduct.js.

An example of what I am trying to do:

// Search Array: UPC, SKU, SKU respectively.
var searchParams = ['342421111', '77HE2', 'U7IA2'];

// Declare var to hold search results.
var searchResults = {};

// For each value in array, get me results to work with.
for(i=0; i < searchParams.length; i++ ) {

    Product.find({"UPC": searchParams[i]}).exec(function (err, results){
        if(results.length >= 1) {
            data[searchParams[i]] = results;
        } else {
            vendorProduct.find({"SKU": searchParams[i]}).exec(function (err, results){
                if(results.length >= 1) {
                    data[searchParams[i]] = results;
                } else {
                    data[searchParams[i]] = "No results.";                    
                }
            });
        }
    });

}


console.log(searchResults);
// This should return something like the below:

{
    '342421111': [results inside],
    '77HE2': [results inside],
    'U7IA2': [results inside]
}

I have looked into options like lodash and async.js but I am not sure it solves what I am looking to do.

I am hopeful that one of you magical wizards can help me out!

Ad

Answer

Ad

Take a look at async.map().

Usage would be something along the lines of...

var searchParams = ['342421111', '77HE2', 'U7IA2'];

async.map(searchParams, function(param, next) {
    Product.find({ UPC: param }).exec(function(err, results) {
        if (err) return next(err);

        if (results.length) return next(null, results);

        vendorProduct.find({ SKU: param }).exec(function(err, results) {
            if (err) return next(err);

            if (results.length) return next(null, results);

            next(null, 'No results');
        });
    });
}, function(err, searchResults) {
    if (err) {
        // handle the error
        return;
    }

    console.log(searchResults);
});
Ad
source: stackoverflow.com
Ad