How to return multiple Mongoose collections in one get request?

I am trying to create an answer that returns the same collection sorted on 3 different columns. Here is the code I currently have:

var findRoute = router.route("/find")
findRoute.get(function(req, res) {
  Box.find(function(err, boxes) {


As you can see, we make one receive request, request for boxes and then sort them by itemCount

at the end. This doesn't work for me because the request only returns one JSON collection, sorted by itemCount


What if I want to return two more collections, sorted, say, name

and size

properties - all in one request?


source to share

3 answers

Create an object to encapsulate information and bind your queries find

, for example:

var findRoute = router.route("/find");
var json = {};

findRoute.get(function(req, res) {
  Box.find(function(err, boxes) {
    json.boxes = boxes;

    Collection2.find(function (error, coll2) {
      json.coll2 = coll2;

      Collection3.find(function (error, coll3) {
        json.coll3 = coll3;



Just do the appropriate error checking.

This is disgusting and makes your code hard to read. Try adapting this logic with modules like async

or even promises ( Q

and bluebird

are good examples.)



If I understand well, you need something like this: return Multiple collections with mongodb

Tell me if it helps.




You tried?

Box.find().sort("-itemCount").exec(function(err, boxes) {


Also to sort the results based on two or more fields, you can use:

.sort ({name: 1, size: -1})

Let me know if it helps.



All Articles