i using nodejs+express+mongoose. assuming have 2 schemas , models in place: "fruits" , "vegetables".
assuming have following:
var testlist = ["tomato", "carrot", "orange"]; var convertedlist = []; // assume res "response" object in express
i wan able check each item in array against "fruits" , "vegetables" collections respectively , insert them converted list tomato, carrot, , broccoli replaced respective documents.
below have pseudocode of think be, know not how this.
for(var = 0; < testlist.length; i++) { var fruitfind = fruit.find({"name":testlist[i]}); var vegfind = vegetables.find({"name":testlist[i]}); // if fruit if(fruitfind) { convertedlist.push(fruitfindresults); } // if vegetable else if(vegfind) { convertedlist.push(vegfindresults); } // if identified fruit , vegetable (assume tomato doc listed under both fruit , vegetable collections) else if (fruitfind && vegfind) { convertedlist.push(vegfindresults); } } // converted list should contain appropriate docs found. res.send(convertedlist) // appears return empty array... how deal waiting callbacks finish fruitfind , vegfinds?
what best way this? or possible?
assuming there's 1 of each fruit/vegetable , intended push veggie that's found in both collections twice.
var async = require("async"), testlist = ["tomato", "carrot", "orange"]; async.map(testlist, function (plant, next) { async.parallel([function (done) { fruit.findone({"name": plant}, done); }, function (done) { vegetables.findone({"name": plant}, done); }], function (err, plants) { // edited: before (err, fruit, veggie) wrong next(err, plants); }); }, function (err, result) { var convertedlist = [].concat(result); res.send(convertedlist); });
note: haven't tested code, should work. the async module excellent managing callbacks btw.
update
to each fruit once, async.parallel callback have rewritten this:
function (err, plants) { next(err, plants[0] || plants[1]); }
and there's no concat needed anymore in .map callback:
function (err, result) { res.send(result); }
Comments
Post a Comment