【问题标题】:Get data from multiple collections in mongoose?从猫鼬的多个集合中获取数据?
【发布时间】:2016-12-12 11:15:22
【问题描述】:

我有两个集合,即 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],这不是预期的结果。我在这里做错了什么? 还有其他解决办法吗??

【问题讨论】:

    标签: javascript node.js mongodb asynchronous mongoose


    【解决方案1】:

    您可以在 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 }
      ]
    }
    

    【讨论】:

    • 猫鼬有什么东西吗?
    • 就像我说的那样,我正在使用 for 循环并且只需要 Employee 集合中的一个字段,所以您认为聚合和 $lookup 是正确的方法吗?此外,我自己添加了一个 Id 字段,因此我不使用 MongoDb 提供的默认 Id
    • 没错。 $lookup 避免了 for 循环,它在 mongodb 3.2 olny 中可用。它是 mongodb 中的最新命令 .. $lookup 只是在另一个集合中查找数据的方法
    • 你能帮我实现这是猫鼬吗?我该怎么办?
    • 嘿,这个真的不会去任何地方!
    【解决方案2】:

    在这种情况下,我会使用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

    【讨论】:

      猜你喜欢
      • 2018-12-20
      • 1970-01-01
      • 1970-01-01
      • 2020-08-14
      • 2020-12-17
      • 1970-01-01
      • 1970-01-01
      • 2020-03-10
      • 2020-03-28
      相关资源
      最近更新 更多