使用Node.js和尚和MongoDB链接嵌套的异步查找 [英] Chaining nested asynchronous finds with Node.js monk and MongoDB
问题描述
我想使用Node.js和尚和MongoDB,模仿一个表联接:
Using Node.js monk and MongoDB, I want to mimic a table join:
- 在集合A上查找
- 对于每个结果X,在集合B中进行查找,然后更新X
- 返回更新的结果列表
和尚中数据库命令的异步特性给我带来麻烦.
这是我的初始代码.这是行不通的,因为第二次调用find
会立即返回promise,
并且xs
中的结果会在响应中发送,然后才能进行更新.
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});
});
我觉得我应该在这里使用Promise链接,但是我不知道该怎么做. 任何帮助将不胜感激.
I feel like I should use promise chaining here, but I cannot figure out how to do it. Any help would be greatly appreciated.
推荐答案
我认为我是通过此答案启发来解决的:
var db = require('monk')('localhost/mydb');
// Initial find
db.get('collection').find({}, function(e,xs) {
// Get inner finds as a list of functions which return promises
var tasks = xs.map(function(x){
return function() {
return coll_b.find({a_id:x._id}, function(e,bs) {
a['bs'] = bs;
});
}
});
// Chain tasks together
var p = tasks[0](); // start the first one
for(var i = 1; i < tasks.length; i++) p = p.then(tasks[i]);
// After all tasks are done, output results
p.then(function(_x){
res.json({'results':xs});
});
});
我仍然认为可以使用chain()
将此代码最小化,但至少可以按预期工作.
I still feel like this code could be minimised by using chain()
, but at least this works as expected.
注意:我意识到对每个结果进行第二次查找不一定有效,但这不是我的关注.
Note: I realise that performing a second find for each result is not necessarily efficient, but that's not my concern here.
这篇关于使用Node.js和尚和MongoDB链接嵌套的异步查找的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!