user3731342
user3731342

Reputation: 61

How to return multiple Mongodb Collections in one app.get request?

I need to load two sets of data from two different mongodb collections onto one page.
My route page that makes the request through mongoose looks like this

app.get('/testPage', function(req,res){
    dbReadOne.find({}, '', function(error, dataOne){
        res.json(dataOne);
    });
    dbReadTwo.find({},'', function(error, dataTwo){
        res.json(dataTwo);
    });
});

My Angular factories look like this

app.factory('dataOneFactory', function($resource){
    return $resource('testPage/:dataOne', {}, {
        query: { method: 'GET', params:  {symbol: 'dataOne'}, isArray: true}
    })
});
app.factory('dataTwoFactory', function($resource){
    return $resource('testPage/:dataTwo', {}, {
        query: { method: 'GET', params:  {customList: 'dataTwo'}, isArray: true}
    })
});

I'm completely lost on how to do this. I'd appreciate any advice I can get on this issue. Thanks.

Upvotes: 4

Views: 904

Answers (1)

Rajika Imal
Rajika Imal

Reputation: 655

Since Node.js is asynchronous in nature, dbReadOne.find function runs asynchronously, therefore you should call the next dbReadOne.find in the callback of first dbReadOne.find function.

Example:

app.get('/testPage', function(req, res){
     dbReadOne.find({}, '', function(errorOne, dataOne){
         if(errorOne)
            throw new Error(errorOne);
         dbReadTwo.find({},'', function(errorTwo, dataTwo){
            if(errorTwo)
                throw new Error(errorTwo);
            res.json({
                dataOne: dataOne,
                dataTwo: dataTwo
            });
         });
     });
});

Upvotes: 1

Related Questions