如何在一个 get 请求中 return 多个 Mongoose 集合?
How to return multiple Mongoose collections in one get request?
我正在尝试生成 return 同一个集合按 3 个不同列排序的响应。这是我目前拥有的代码:
var findRoute = router.route("/find")
findRoute.get(function(req, res) {
Box.find(function(err, boxes) {
res.json(boxes)
}).sort("-itemCount");
});
如您所见,我们正在发出单个 get 请求,查询 Boxes,然后在最后按 itemCount
对它们进行排序。这对我不起作用,因为请求仅 return 是按 itemCount
排序的单个 JSON 集合。
如果我想 return 按 name
和 size
属性排序的另外两个集合 - 都在同一个请求中,我该怎么办?
你试过了吗?
Box.find().sort("-itemCount").exec(function(err, boxes) {
res.json(boxes)
});
还可以根据 2 个或更多字段对结果进行排序:
.sort({名称: 1, 大小: -1})
如果有帮助请告诉我。
如果我理解得很好,你想要这样的东西:return Several collections with mongodb
如果有帮助请告诉我。
再见。
创建一个对象来封装信息并链接您的 find
查询,例如:
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");
});
只需确保进行适当的错误检查。
这有点丑陋,使您的代码难以阅读。尝试使用像 async
or even promises (Q
and bluebird
这样的模块来调整此逻辑是很好的例子)。
我正在尝试生成 return 同一个集合按 3 个不同列排序的响应。这是我目前拥有的代码:
var findRoute = router.route("/find")
findRoute.get(function(req, res) {
Box.find(function(err, boxes) {
res.json(boxes)
}).sort("-itemCount");
});
如您所见,我们正在发出单个 get 请求,查询 Boxes,然后在最后按 itemCount
对它们进行排序。这对我不起作用,因为请求仅 return 是按 itemCount
排序的单个 JSON 集合。
如果我想 return 按 name
和 size
属性排序的另外两个集合 - 都在同一个请求中,我该怎么办?
你试过了吗?
Box.find().sort("-itemCount").exec(function(err, boxes) {
res.json(boxes)
});
还可以根据 2 个或更多字段对结果进行排序:
.sort({名称: 1, 大小: -1})
如果有帮助请告诉我。
如果我理解得很好,你想要这样的东西:return Several collections with mongodb
如果有帮助请告诉我。
再见。
创建一个对象来封装信息并链接您的 find
查询,例如:
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");
});
只需确保进行适当的错误检查。
这有点丑陋,使您的代码难以阅读。尝试使用像 async
or even promises (Q
and bluebird
这样的模块来调整此逻辑是很好的例子)。