环回:不异步查询多个集合

时间:2017-08-19 14:40:02

标签: javascript mongodb asynchronous model loopback

我有一个包含2个集合的MongoDB数据库:Customer和Order。这些模型在Loopback中的关系如下:Customer -hasMany->订单&订单-belongsTo->客户(因此订单具有foreignKey customerId)。 我需要查询所有年龄为20岁的客户的订单。但我很惊讶地注意到Loopback不支持这种查询。我搜索了很多,甚至“包含”选项也不支持我想要的格式作为最终结果,并且不能按年龄功能(Loopback-doc-about-it)组合到过滤器。然后,我编写了一个进行2次查询的远程方法:第一个查找具有特定年龄的所有客户(基本位于过滤器中),另一个查找该列表中的每个客户以查找其订单(基本上针对每个索引,进行搜索)在Orders集合中,其中customerId等于索引的客户id)

这是customer.js文件:

'use strict';

module.exports = function(Customer) {
    var app = require('../../server/server');  

 /**
 *
 * @param {number} age
 * @param {Function(Error, array)} callback
 */

    
    Customer.getOrdersByAge= function(age, callback) {
        var customers;
        
        var filter= { where: { 'age': age } };

        var Order=app.models.Order;
        var orders;

        var elementary_orders;


        Customer.find(filter, function(err, items) { 
            if (err !==null){
                console.log("error1");
                return callback(err);
            }
            console.log("items: "+ items);
            customers=items;



    
            for (let i of customers){
                console.log(i+": "+i.id+" -lenght: "+customers.length);
                var filter_order= { where: { 'customerId': i.id+'' } };
                
                Order.find(filter_order, function(err2, items_orders) { 
                    if (err2 !==null){
                        console.log(i+": "+"error2");
                        return callback(err2);
                    }
                    elementary_orders= items_orders;
                    orders=elementary_orders;
                    console.log("elementary_orders: "+ elementary_orders);
                    console.log("orders now: "+ elementary_orders);
                });
            
            }
            console.log("-> orderssss: "+ orders);
            callback(null,orders);
        });   



        }

};
  

但后来我发现了另一个问题,订单总是未定义的。看来,由于“查找”查询是异步的,因此订单保持不定义。所以,我找了一种让它同步的方法(但这是不可能的,因为它的Loopback的精神始终是异步的)和一种通过npm(async package来控制流量的方法,但即使在尝试eachOf实用程序之后,订单也是仍未定义。

我不仅想知道如何才能使这个简单的查询工作,而且为什么它不可能实现呢?我是否违反了与Loopback模型相关的任何概念或架构模式?但是,查询多个集合是很常见的事情。

谢谢:)

1 个答案:

答案 0 :(得分:0)

您可以在客户身上使用async.map来修补模型并获取添加的订单。

async.map(customers, function(customer, mapCallback) {
  Order.find(params, function (orders, error) {
    if(ordersError) {
      mapCallback(null, ordersError);
    }

    customer.orders = orders;
    mapCallback(customer);
  });
}, callback); //This callback is the main from the remote method.