从mongoose的多个集合中获取数据?

时间:2016-08-06 00:25:11

标签: javascript node.js mongodb asynchronous mongoose

我有两个集合,即Orders和Employee。我首先使用客户ID从某个客户的Orders集合中查找所有订单,然后需要使用结果中的字段来查找Employee集合中的数据。我面临的问题是我从Orders得到的结果是一个数组,所以我需要使用for循环遍历它,然后在for循环内找到Employee数据。订单的第一部分有效但第二部分并不总是我的0数组值。

        async.waterfall([
        function(callback) {
            Order.find({ user_id: req.body.id}, {sort: { id: -1 }}, function(err, order) {
                callback(null, order);
            });
        },
        function(order, callback) {
            for(var i = 0; i < order.length; i++) {
                Employee.find({id: order[i].id}, 'field', function(err, employee) {
                    if (employee.length > 0) {
                        order[i].field = employee[i].field;
                    }
                    order[i].id = order[i].otherid;
                    regs.push(order[i]);
                });
            callback(null, regs);
            }
        }], function (err, result) {
            res.send(result);
        });

但结果如下:[0],这不是预期的结果。我在这做错了什么? 还有其他解决办法

2 个答案:

答案 0 :(得分:0)

您可以在mongodb中尝试$ lookup。我认为对你有帮助

我有这样的订单收集

{ "_id" : 1, "item" : "abc", "price" : 12, "quantity" : 2 }
{ "_id" : 2, "item" : "jkl", "price" : 20, "quantity" : 1 }
{ "_id" : 3  }

另一个集合就是这样的库存

{ "_id" : 1, "sku" : "abc", description: "product 1", "instock" : 120 }
{ "_id" : 2, "sku" : "def", description: "product 2", "instock" : 80 }
{ "_id" : 3, "sku" : "ijk", description: "product 3", "instock" : 60 }
{ "_id" : 4, "sku" : "jkl", description: "product 4", "instock" : 70 }
{ "_id" : 5, "sku": null, description: "Incomplete" }
{ "_id" : 6 }

使用聚合查找所有订单数据然后我需要使用订单收集字段查找库存数据

db.orders.aggregate([
    {
      $lookup:
        {
          from: "inventory", //another collection name
          localField: "item", // order collection field
          foreignField: "sku", // inventory collection field
          as: "inventory_docs"
        }
   }
])

输出

{
  "_id" : 1,
   "item" : "abc",
  "price" : 12,
  "quantity" : 2,
  "inventory_docs" : [
    { "_id" : 1, "sku" : "abc", description: "product 1", "instock" : 120 }
  ]
}
{
  "_id" : 2,
  "item" : "jkl",
  "price" : 20,
  "quantity" : 1,
  "inventory_docs" : [
    { "_id" : 4, "sku" : "jkl", "description" : "product 4", "instock" : 70 }
  ]
}
{
  "_id" : 3,
  "inventory_docs" : [
    { "_id" : 5, "sku" : null, "description" : "Incomplete" },
    { "_id" : 6 }
  ]
}

答案 1 :(得分:0)

在这种情况下,我会使用populate()。确保这一点有点棘手,因为你没有在这里发布你当前的模式,但是我们暂时假设你有这样的设置:

const mongoose = require('mongoose'),
      Schema   = mongoose.Schema;

var orderSchema = new Schema({
    user : { type: Schema.ObjectId, ref: 'User' }, 
    employee : {type: Schema.ObjectId, ref: 'Employee' }
   /* Other things */ 
}); 
mongoose.model('Order', orderSchema);

现在,鉴于该设置,您可以这样查询:

Order.find({user: new ObjectId(req.body.id)}).sort({id:-1}).populate('employee').exec(function(e, orders){
  /*  whatever  you want to do with the orders, each of which will have the employee data filled in by here */
}); 

如果您只想从Employee模型中提取一些字段,可以像.populate('employee','name')那样提取。完整文档位于mongoose site