3

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?

Dylan Richards
  • 796
  • 3
  • 9
  • 26

3 Answers3

4

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).

Rodrigo Medeiros
  • 7,814
  • 4
  • 43
  • 54
3

If I understand well, you want something like that : return Several collections with mongodb

Tell me if that helps.

Bye.

Charly
  • 125
  • 8
  • Or you can use promises for this. http://stackoverflow.com/questions/22794827/mongoose-and-promises-how-to-get-an-array-of-query-results – vanadium23 Apr 23 '15 at 13:48
  • This appears to be what I need. I will circle back with results in a bit. @vanadium23 -- I'll check out your suggestion as soon as I'm done with Charly's. Thanks so much! – Dylan Richards Apr 23 '15 at 13:50
  • The link is broken as of 5/2018. This is why we ask you to post and answer instead of just a link. If you add an actual answer you won't suffer the wrath of downvotes! :-) – Rap May 07 '18 at 21:39
  • Found the content of the link: https://web.archive.org/web/20150108205205/http://www.kdelemme.com:80/2014/07/28/read-multiple-collections-mongodb-avoid-callback-hell – dusan Aug 09 '18 at 14:49
0

Have you tried ?

Box.find().sort("-itemCount").exec(function(err, boxes) {
    res.json(boxes)
});

Also for sorting your results based on 2 or more fields you can use :

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

Let me know if that helps.

Panos
  • 29
  • 1
  • 4