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) {
res.json(boxes)
}).sort("-itemCount");
});
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
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;
res.json(json);
}).sort("-size");
}).sort("-name");
}).sort("-itemCount");
});
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.)
source to share
If I understand well, you need something like this: return Multiple collections with mongodb
Tell me if it helps.
Bye.
source to share