Nodejs + mongodb中REST API的自定义URL

所以我在nodejs api里有下面的mongoose模式:

var profileschema = new mongoose.Schema({ name: { type: String }, surname: { type: String }, id: { type: String } }); 

以下路线:

  var profile = express.Router(); profile.route('/profile') .get(profilecrtl.findAllProfile) .post(profilecrtl.addProfile); 

我可以制作其他路线,如/ profile /:id ,他们完美的工作。

但我想生成自定义的url,取决于用户所要求的参数和想要的方法,而不必编码每个案例。 例如:

  • / profile?id = 1234应该给我有关id = 1234configuration文件的完整信息

 { id: '1234', name: 'john' surname: 'wicked' } 

  • / profile?id = 1234&name = john应该给我像以前一样的完整configuration文件

 { id: '1234', name: 'john' surname: 'wicked' } 

  • / profile?id = 1234&fields = name应该给我一个id = 1234 profile的名字

 { name: 'john' } 

同一个案例中有没有强大的方法可以做到这一点,所以如果将来有任何改变,它可以轻松扩展。

由于您使用的是Express,因此您应该使用req.query获取具有所请求参数的对象。

 profile.get('/profile', function (req, res) { var query = req.query; //Depending on what the query contains, find stuff in your DB with mongoose! }); 

req.query是一个包含请求的所有查询参数的JSON对象,所以像这样的请求

/个人资料?ID = 1234&域=名称

会导致类似的JSON对象

 { id: '1234', fields: 'name' } 

从中可以创build数据库查询。

我同意丹尼尔的观点,他没有回答你的问题。 这里是一个例子,如何做你要找的东西,你将不得不自己做mongoose查询。

  profile.get('/profile', function (req, res) { var query = req.query; if(query.id&& !query.field) { //the user is asking for the full profile }else if(query.field) { switch(query.field) { case "name": //the user is asking for the field name break; } }else{ } });