i cant merge the result of each FIND functions in this code :
this.result = [];
_products.find().exec(function (err,products) {
this.products = products;
var productsCollection = [];
for(i=0;i<products.length;i++) {
_prices.find({uname:products[i].uname},function(err,prices){
var resultItem = {product:products[i],prices:prices}
this.result.push(resultItem)
}.bind(this))
}
res.json(200, this.result);
}.bind(this) );
there is no error ... but the response is an empty array :(
please help ... how can i merge results ?
You're calling res.json before you've recieved the result of _prices.find({uname..., since .find is asynchronous. The simple solution is to use async to loop through the array and call res.json when all results are recieved.
var async = require('async');
this.result = [];
_products.find().exec(function (err, products) {
// async.map takes an array and constructs a new array from it
// async.each and this.result.push() would also work but I find .map to be cleaner
async.map(products, function (product, next) {
_prices.find({ uname: product.uname }, function(err, prices){
// By passing the object to next here it will be passed to the
// final callback below
next(err, { product: product, prices: prices });
});
}, function (err, result) {
// This callback will nicely wait until all queries above has finished
this.result = result;
res.json(200, result);
});
}.bind(this));