如何在一个GET请求返回多个猫鼬的集合? [英] How to return multiple Mongoose collections in one get request?

查看:101
本文介绍了如何在一个GET请求返回多个猫鼬的集合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想生成返回由3个不同的排序列同一个集合的响应。这里的code我目前有:

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");
});

正如你所看到的,我们正在做一个GET请求,查询的复选框,然后通过 ITEMCOUNT 在结束对它们进行排序。这不适合我,因为请求只返回一个JSON集合,由 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?

推荐答案

克里特岛的对象来封装信息和链中的找到查询,如:

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.

这是一种uggly,让您的code有种难以阅读。尽量去适应使用类似 模块这个逻辑异步 甚至承诺( 问: 和< A HREF =htt​​ps://www.npmjs.com/package/bluebird相对=nofollow> 蓝鸟 就是很好的例子)。

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

这篇关于如何在一个GET请求返回多个猫鼬的集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆