可选的搜索参数与猫鼬

Optional search parameters with mongoose?

本文关键字:参数 搜索      更新时间:2023-09-26

我是一个没有经验的web开发人员,我在制作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张图像,标题"猫A","猫B"等,类别为空([])。然后我们希望从结果3开始并显示6个结果。这是我的代码,我不确定如何在
中添加额外的功能。

您可以根据提供的参数根据需要构建查询。我对如何提供参数有点猜测,但这里有一个例子:

// 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);
});