基于Express / Mongoose REST API的GET参数进行路由

我正在试图在使用Mongo + ExpressdeviseREST API时如何处理更复杂的查询。 不幸的是,我所能find的所有例子都太简单了。 这个问题的目的是一个简单的例子。 我有团体,我有用户。 在每个小组内,有成员和1个领导。 为了简单起见,我将排除中间件和后/放/删除function。

路线看起来像这样:

app.get('/groups', groups.all); app.get('/groups/:groupId', groups.show); app.param('groupId', groups.group); 

控制器看起来像这样:

 /** * Module dependencies. */ var mongoose = require('mongoose'), Group = mongoose.model('Group'), _ = require('lodash'); /** * Find group by id */ exports.group = function(req, res, next, id) { Group.load(id, function(err, group) { if (err) return next(err); if (!group) return next(new Error('Failed to load group ' + id)); req.group = group; next(); }); }; /** * Show a group */ exports.show = function(req, res) { res.jsonp(req.group); }; /** * List of Groups */ exports.all = function(req, res) { Group.find().sort('-created').populate('user', 'name username').exec(function(err, groups) { if (err) { res.render('error', { status: 500 }); } else { res.jsonp(groups); } }); }; 

然后模型会看起来像这样:

 var mongoose = require('mongoose'), Schema = mongoose.Schema; /** * Group Schema */ var GroupSchema = new Schema({ created: { type: Date, default: Date.now }, updated: { type: Date, default: Date.now }, enableScores: { type: Boolean, default: false }, name: { type: String, default: '', trim: true }, creator: { type: Schema.ObjectId, ref: 'User' }, commissioner: { type: Schema.ObjectId, ref: 'User' } }); /** * Validations */ GroupSchema.path('name').validate(function(name) { return name.length; }, 'Name cannot be blank'); /** * Statics */ GroupSchema.statics.load = function(id, cb) { this.findOne({ _id: id }) .populate('creator', 'name username') .populate('commissioner', 'name username') .exec(cb); }; mongoose.model('Group', GroupSchema); 

如果我想根据专员字段查询REST API,该怎么办? 或创作​​者,名称或创build的字段? 这可能使用Express的路由,如果是这样,是否有最佳做法?

看起来好像不是处理这些独特的情况,最好是通用的返回所有基于req.params匹配的组,因为如果模型晚一点改变,我不需要更新控制器。 如果这是这样做的,那么也许修改all()函数来查找基于req.params的解决scheme? 所以,如果没有提供任何东西,那么它会返回所有的东西,但是当你提供更多的参数时,它可以深入你正在寻找的东西。

我会build议使用req.query匹配模式中的字段。 如果您发送像/groups?name=someGrp&enableScores=1req.query将如下所示…

 {name: "someGrp", enableScores: 1} 

你可以把这个对象传递给find方法

 Group.find(req.query, callback); 

这种方法适用于简单的属性匹配查询,但是对于比较和数组属性等其他内容,您必须编写额外的代码。