How to return multiple Mongoose collections in one get request?

后端 未结 3 984
北恋
北恋 2020-12-21 07:56

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.         


        
相关标签:
3条回答
  • 2020-12-21 08:06

    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.

    0 讨论(0)
  • 2020-12-21 08:07

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

    Tell me if that helps.

    Bye.

    0 讨论(0)
  • 2020-12-21 08:17

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

    0 讨论(0)
提交回复
热议问题