I have this function to get the shops from a mongodb DB.
exports.find_shops = function(selector, fields, limit, skip, cb){
if(typeof fields == 'function'){
limit = 0
cb = fields
fields = {}
skip = 0
}
if(typeof limit == 'function'){
cb = limit
limit = 0
skip = 0
}
if(typeof skip == 'function'){
cb = skip
skip = 0
}
if(typeof selector == 'string'){
limit = 1
selector = {_id: new db.bson_serializer.ObjectID(selector)}
}
console.log('a')
Shop.find(selector, fields).limit(limit).toArray(function(err, shops){
console.log('b')
if(err){
throw new Error(err)
} else {
if(limit == 1){
cb(shops[0])
} else {
cb(shops)
}
}
})
}
The output I get in the console looks like
a
b
b
whereas I expect it to be
a
b
Whats wrong here?
EDIT:
exports.search = function(products, location, skip, cb){
if(typeof skip == 'function'){
cb = skip
skip = 0
}
this.find_shops({
products: {
$in: products
},
$or: [{
location: { $near: location , $maxDistance: 2 }
},
{
delivery: -1
},
{
delivery: {$lt: 2}
}]
}, {name: 1, location: 1, delivery: 1, products: 1}, 10, skip, function(shops){
shops.forEach(function(i,shop){
shops[i] = _.intersect(shop.products, products)
})
// now we have the products that user needs from this shop.
var combos = []
shops.forEach(function(i,shop1){
var combo = [i]
var p = shop1.products
shops.forEach(function(j,shop2){
if(i > j){
return
} else {
var newprod = _.intersect(p,shop2.products)
if(newprod.length == shop2.products.length){
return
} else {
p.push(shop2.products)
p = _.uniq
combo.push(j)
if(p.length == products.length){
combos.push(combo)
}
}
}
})
})
cb(combos)
})
}
Presumably the
toArray()function converts its input into an array, and then passes each element of the array to the closure function in its parameter?If that’s the case, then the result you’re seeing could be caused simply by
toArray()generating an array of two items. That doesn’t needs anything to be recursive in any way.