我是一位没有经验的网络开发人员,而且我在制作API方面遇到了麻烦。
此API应该能够采用这些参数;所有参数都应该是可选的(标题,类别),我应该能够限制我得到的结果数量,即从哪里开始结果以及我应该返回多少结果。
app.get('/images', function(req, res) {
// var searchKey = req.query.keyword;
console.log("hello!");
var regex = new RegExp(req.query.q, 'i');
return Image.find({
title: regex
},function(err, q) {
console.log("do this");
return res.send(q);
});
});
例如,假设我们有10张图片标题" Cats A"," Cats B"等等类别为空([])。然后我们想从结果3开始并显示6个结果。 这是我的代码,我不确定如何添加额外的功能。
答案 0 :(得分:0)
You can build up your query as needed based on the supplied parameters. I'm guessing a bit with how the parameters are provided, but here's an example:
// Build up the query conditions based on the supplied parameters (if any).
var conditions = {};
if (req.query.q) {
// Match the query string against the either the title or categories fields
var regx = new RegExp(req.query.q, 'i');
conditions.$or = [
{title: regx},
{categories: regx}
];
}
var query = Image.find(conditions);
// Support optional skip and limit parameters.
if (req.query.skip) {
query = query.skip(req.query.skip);
}
if (req.query.limit) {
query = query.limit(req.query.limit);
}
// Execute the assembled query.
return query.exec(function(err, q) {
console.log("do this");
return res.send(q);
});