【问题标题】:Mongojs fetching data from two collections and merging the resultMongojs 从两个集合中获取数据并合并结果
【发布时间】:2013-05-15 22:10:42
【问题描述】:

我是一名 mongodb 新手,非常感谢您对下面描述的这个问题的帮助。

我有两个集合“用户”和“包”。用户集合方案有 {username, firstname, lastname},包集合模式有 {username, bagname, bagimage}。

在获取用户包时,我还想显示名字和姓氏。我的问题是我似乎无法正确构建查询。我正在使用 nodejs 和 mongojs 驱动程序。以下是我获取所有行李的查询

  thmConfig.db.bags.find({status: "1"}).sort({$natural:-1}, function(err, data) 
{
        var bagList = '{"bags":[';


     if( err || !data) res.send('[{"status": "0"}]');
        else data.forEach( function(innerData) {
            console.log(innerData.username);
            bagList += JSON.stringify(innerData)+",";

                 /*
                   This is where I would lke to also append the firstname from the 
                users collection

                   */

        });

    console.log(bagList.slice(0,1));
    res.write(magList.slice(0,-1));
    res.end(']}');
});     

我将非常感谢任何有关此的帮助或指示。我无法选择更改驱动程序,所以我现在特别想使用 mongojs 来实现。

感谢和问候, 蒂塔什

【问题讨论】:

  • 你也在使用 express.js 吗?哪个版本?另请注意,mongojs 调用是异步的。因此,如果您想进一步调用它(例如为每个包获取用户数据),您可能需要进行一些重构。
  • 是的,我使用的是 express 3.0.0rc4。通过重构,您是否建议从 mongojs 转移到另一个驱动程序?

标签: javascript node.js mongodb mongojs


【解决方案1】:

我认为除了从用户集合中读取并以编程方式执行此“加入”操作之外,您别无选择。 您可以读取每个包的用户文档(在循环内),或者提前将整个用户集合读取到一个对象中,并通过用户名进行查找

【讨论】:

    【解决方案2】:

    您可以为此使用$in 运算符。

    伪代码(ish):

    // get an array of bags matching your query
    db.bags.find({status: "1"}).sort({$natural:-1}, function(err, bags) {
      // get a list of usernames from the bags:
      var usernames = bags.map(function(bag) { return bag.username; });
    
      // perform query on user table: find all users for which we have a bag
      db.users.find({ username : { $in : usernames } }, function(err, users) {
        // create a mapping of username -> first name for easy lookup
        var usernames = {};
        users.forEach(function(user) {
          usernames[user.username] = user.firstname;
        });
    
        // map first names to bags
        bags.forEach(function(bag) {
          bag.firstname = usernames[bag.username];
        });
    
        // done: return it as JSON (no need to build a JSON string ourselves)
        res.send({ bags : bags });
      });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-16
      • 1970-01-01
      • 2021-06-19
      • 1970-01-01
      相关资源
      最近更新 更多