【发布时间】:2014-01-04 03:19:25
【问题描述】:
假设我有一个这样的网址:
http://dev.myserver.com/systems?system_type.category=Penetration
命中以下控制器:
exports.findAll = function(req, res) {
System.find(req.query, function(err, systems) {
res.send(systems);
});
};
然后使用 Node、Express、MongoDB 和 Mongoose 自动返回下面的集合:
[{
"_id": "529e5f29c128685d860b3bad",
"system_number": "123",
"target_country": "USA",
"system_type": {
"category": "Penetration",
"subcategory": ["Floor", "Wall"]
}
},{
"_id": "999e5f29c128685d860b3bad",
"system_number": "456",
"target_country": "Canada",
"system_type": {
"category": "Penetration",
"subcategory": ["Floor", "Wall"]
}
}]
现在,如果我想要按“target_country”排序的结果,那么“自动魔术”这样做的“最佳实践”是什么?
Mongoose/Express 是否希望为我执行某些参数/语法?或者,这是我必须专门为它编码的情况吗? (那会杀死已经存在的“自动魔法”功能。)
谢谢!
更新:这对我有用。
exports.findAll = function(req, res) {
// Sort Ascending:
http://dev.dom.com/systems?system_type.category=Penetration&sort=system_number
// Sort Descending:
http://dev.dom.com/systems?system_type.category=Penetration&sort=-system_number
// Default sort ascending on system_number:
http://dev.dom.com/systems?system_type.category=Penetration
var sort_param = req.query.sort ? req.query.sort : 'system_number';
System.find().sort(sort_param).find(function(err, menus) {
res.send(menus);
});
};
我猜我哪里出错了,我认为我应该使用过滤器查找然后排序,而不是查找全部,排序然后使用过滤器再次查找。我猜我的头脑仍然围绕着整个“回调哲学”。
【问题讨论】:
-
不是重复的。在另一个线程中,排序参数已知为“日期”。这里,不知道GET请求查询参数中提供的排序参数会是什么。我建议它是“target_country”,但它可以是任何有效字段。 (为了清楚起见,我只在示例中展示了一些 - 还有更多。)
标签: node.js mongodb sorting mongoose