Drum
Drum

Reputation: 507

Render The Results from Two Mongo Queries on One Page

I've recently started playing around with MongoDB and Node.js/Express and I'm still having difficulties grasping some of the concepts.

Excuse the newbie question. I couldn't find an existing answer which covered what I'm trying to learn.

It's quite simple really, I just want to output the results from two separate mongo queries on a single page. I don't need to group or otherwise join the data in any way, I just need to display the results of each query on the one page.

So, I can query and display a single query no problem, but I fall down with the second query because the example code I have does the query in the .js file and renders the page and passes the result as an array (if I'm understanding properly) so

        var collection = db.collection('photographers');
        collection.find({}).toArray(function(err,result){
            if(err){
                console.log("Error retrieving records");
                res.send(err);
            }else if (result.length){
                console.log("Success");
                res.render('ptlist',{
                    "ptlist":result
                });
            }else{
                res.send('No Documents');
            }
            db.close();

renders my view 'ptlist' and passes the result in the array ptlist.

I can't work out how to then perform another query to a different collection and have the array of results also available to use in the view 'ptlist'.

An (simple) examples would be gratefully received. Otherwise pointers to where I might find some nicely commented examples would also be cool.

Sorry if this is a stupid question. It's still very early days for mew with this stuff.

Upvotes: 0

Views: 868

Answers (1)

strah
strah

Reputation: 6732

This will be the easiest solution, based on your code.

It's not great, there is a callback hell, but it will work, assuming that the finalResult has a structure which can be consumed by the view.

To make things nicer you could use async for example. Or co and MongoDB ES6 yield as in their sample code.

var collection = db.collection('photographers');
collection.find({}).toArray(function(err,result){
    var finalResult = {};
    if(err){
        console.log("Error retrieving records");
        res.send(err);
    } else if (result.length){
        console.log("Success");
        finalResult.plist = result;
        collection.find({/* another query */}).toArray(function(err,result){
            finalResult.anotherKey = result;
            res.render('ptlist',{
                "ptlist":finalResult
            });
        });
    }else{
        res.send('No Documents');
    }
    db.close();
});

Upvotes: 2

Related Questions