Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return multiple Mongoose collections in one get request?

I am trying to generate a response that returns the same collection sorted by 3 different columns. Here's the code I currently have:

var findRoute = router.route("/find")
findRoute.get(function(req, res) {
  Box.find(function(err, boxes) {
    res.json(boxes)
  }).sort("-itemCount");
});

As you can see, we're making a single get request, querying for the Boxes, and then sorting them by itemCount at the end. This does not work for me because the request only returns a single JSON collection that is sorted by itemCount.

What can I do if I want to return two more collections sorted by, say, name and size properties -- all in the same request?

like image 385
Dylan Richards Avatar asked Dec 01 '25 06:12

Dylan Richards


1 Answers

Crete an object to encapsulate the information and chain your find queries, like:

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;

        res.json(json);
      }).sort("-size");
    }).sort("-name");
  }).sort("-itemCount");
});

Just make sure to do the appropriate error checking.

This is kind of uggly and makes your code kind of difficult to read. Try to adapt this logic using modules like async or even promises (Q and bluebird are good examples).

like image 68
Rodrigo Medeiros Avatar answered Dec 03 '25 19:12

Rodrigo Medeiros



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!