Mongoose: query with array of datas and return single array

I am using Mongoose with Express.js

I have 2 collections:

i)Collection A Schema

  • userId
  • carId

ii) Collection B Schema

  • carId
  • carName

In collection A, I will store how many cars the user has Example: if user XYZ, has 2 car, I will create 2 documents, each with the unique car ID

When a REST get method, is called I want to return with the userID, carID and the carName.

But, I have problem to query multiple collections and combine them into one result!

My current method doesnt work, due to the async of the code:

var totalCar = []
CollectionA.find({
    userId: userId
}, function(err, data){
    /*Wrong code here, how to fix it?????
    for(var i = 0; i < data.length; i++){
        CollectionB.find({
        }, function(err, car){
            totalCar.push(car.carName)
        })
    }*/

    res.json({
        userId: userId,
        car: totalCar
    })
})

How can I query from another collection, inside a query and combine those query from another collection into a single result and send to user?

For you particular question, you can use "$in" query in mongodb.

var totalCar = [];
CollectionA.find({
    userId: userId
}, function(err, data){
    var cardIds = [];
    for(var i = 0; i < data.length; i++){
        cardIds.push(data[i].cardId);
    }
    CollectionB.find({$in:cardIds}, function(err, cards) {
        for (var i = 0; i < cards.length; i++)
            totalCar.push(cards[i].carName);
        res.json({
            userId: userId,
            car: totalCar
        });
    });
});

But in general, if you are looking for a way to execute code in a sync mode, you can look at this module: https://github.com/caolan/async

For using Mongoose:

CollectionA.find({
    userId: userId
}, function(err, data){
    var carIds = [];

    for(var i=0; i < data.length; i++){
          carIds[i] = data[i].carId;
    }

    CollectionB.find()
        .where('carId')     
        .in(cardIds)
        .exec(function(err, carModel){
              ... //get all the carModel in array
})