Skip to content Skip to sidebar Skip to footer

Expressjs: Search Query Api

I want to search through my user repository with a query string. This should return all users with a similar username 'kyogron' and similar email 'kyogron@gmail' GET localhost:3000

Solution 1:

app.get('/users', function(req, res) {
    var query = User.find({});

    Object.keys(req.query).forEach(function(key) {
        query.where(key).regex(newRegExp(req.query[key]));
    });

    /*
    if (req.query.username) {
        query.where('username').regex(new RegExp(req.query.username));
    }
    if (req.query.email) {
        query.where('email').regex(new RegExp(req.query.email));
    }*/

    query.select('username', 'email');
    query.exec(function(err, users) {
        if (err) throw err;
        res.json(users);
    });

});

The first didn't work because I had a typo (.select() not .where()). The second was found in an extra thread

I am still a bit unsure about the chosen approach.

Iterating req.query would allow to make the code reusable (maybe as precondition routing parameter-function) but it is quite susceptible for errors

Post a Comment for "Expressjs: Search Query Api"