stretchy pants
stretchy pants

Reputation: 11

Optional search parameters with mongoose?

I'm an inexperienced web developer and I'm having trouble with making an API.

This API should be able to take these parameters; all parameters should be optional (which are title, categories) and I should be able to limit the number of results I get i.e. where to start the results and how many results I should return.

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

For example, say we have 10 images with title "Cats A", "Cats B", etc and categories as empty ( [ ] ). We then want start from result 3 and display 6 results. This is my code, and I'm not sure how to add the extra functionalities in.

Upvotes: 1

Views: 1871

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311865

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

Upvotes: 1

Related Questions