0
votes

I have a MongoDB database with 2 collections: Customer and Order. These models' relationships in Loopback are as follows: Customer -hasMany-> Order & Order -belongsTo-> Customer (so an order has a foreignKey customerId). I needed to query the orders of all customers that have age 20 for example. But I was surprised to notice that Loopback doesn't support this kind of queries. I searched a lot and even the "include" option doesn't support the format I want to get as a final result and cannot be combined to the filter by age functionality (Loopback-doc-about-it). Then, I wrote a remote method that makes 2 queries: the first one finds all customers who have a certain age (Basic where filter) and the other iterates over every customer in that list to find his orders ( basically for each index, it searches in the Orders collection which ones has customerId equal to the index's customer's id)

Here's customer.js file:

'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);
        });   



        }

};
  

But then I found another problem, orders is always undefined. It appears that since "find" queries are asynchronous, orders stays undefined. So, I looked for a way to make it synchronous (but it was impossible since it's Loopback's spirit to be always asynchronous) and a way to control the flow through npm's (async package but even after trying the eachOf utility, orders is still undefined.

I am wondering not only how can I make this simple query work but also why is it so impossible to implement? Am I violating any conceptual or architectural patterns related to Loopback's models or something? Querying multiple collections is a usual thing to do, though.

Thank you :)

1

1 Answers

0
votes

You can use async.map on the customers to patch the models and get the orders added to them.

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.