使用Node.js和尚和MongoDB链接嵌套的异步查找 [英] Chaining nested asynchronous finds with Node.js monk and MongoDB

查看:100
本文介绍了使用Node.js和尚和MongoDB链接嵌套的异步查找的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Node.js和尚和MongoDB,模仿一个表联接:

Using Node.js monk and MongoDB, I want to mimic a table join:

  1. 在集合A上查找
  2. 对于每个结果X,在集合B中进行查找,然后更新X
  3. 返回更新的结果列表

和尚中数据库命令的异步特性给我带来麻烦. 这是我的初始代码.这是行不通的,因为第二次调用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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆