I have customer scheema in which I am storing customer details with referenceId of address(it is array of addresses for eg one customer can have many addresses). And I have multiple fields like street, area, landmark in address schema. I have to find all customers who's area is viman nagar, kalyani nagar or KP. Further I have to export this result into csv file.
I know one traditional method for doing this is, find all customers, 'populate' their addresses and finally loop through result and modify result with only customers whose address contain viman nagar, kalyani nagar or KP as 'area'.
And for export result into CSV I'll use milan's answer from here.
Can I get customer list in single query without looping through result and modifying result set? or suggest me any good option to achieve this.
var getCustomerToExport = function(req, res) {
var filteredResult = [];
Customer.find().populate('address').exec(function(err, customers){
async.forEach(customers, function(c) {
var newCustomer= c.address.filter(function(a, indx, arr){ return(a.area === 'viman nagar' || a.area === 'kalyani nagar' || a.area === 'KP'); });
if(newCustomer.length > 0)
filteredResult.push(c);
});
res.json(filteredResult);
});
};