Using Node.js monk and MongoDB, I want to mimic a table join:
- Do a find on collection A
- For each result X, do a find in collection B, and update X
- Return updated list of results
The asynchronous nature of database commands in monk is giving me trouble.
This is my initial code. It doesn't work because the second call to find
returns a promise immediately,
and the results in xs
are sent in the response before they can be updated.
var db = require('monk')('localhost/mydb');
db.get('collection').find({}, function(e,xs) {
xs.forEach(function(x){
coll_b.find({a_id:x._id}, function(e,bs) {
a['bs'] = bs;
});
});
res.json({'results':as});
});
I feel like I should use promise chaining here, but I cannot figure out how to do it. Any help would be greatly appreciated.