[英]Custom URL for REST API in Nodejs + mongodb
所以我在nodejs api中有以下猫鼬模式:
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,而不必编写每种情况。 例如:
{
id: '1234',
name: 'john'
surname: 'wicked'
}
{
id: '1234',
name: 'john'
surname: 'wicked'
}
{
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&域=名称
会导致像
{
id: '1234',
fields: 'name'
}
您可以从中创建数据库查询。
我同意丹尼尔(Daniel)的看法,他没有回答您的完整问题。 这是一个示例,该如何做您要寻找的东西,您必须自己进行猫鼬查询。
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{
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.