Expressjs: api search query

I want to search my user repository using the query string.

This should return all users with a similar username "kyogron" and a similar email "kyogron @gmail"

GET localhost:3000/users?username=kyogron&email=kyogron@gmail.com

This should return all users:

GET localhost:3000/users

I already managed to process the routing parameters, but I went in cycles in its optimization:

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

    // to understand how expressjs handles queries:
    // ?username=kyogron&email=kyogron@gmail.com
    // { username: "kyogron", email: "kyogron@gmail.com" }
    //console.log(req.query);

    // this was one idea of optimizing the search query parameters
    // this doesn't work don't know why I always get an array of ALL users
    // even the key and value is right
    Object.keys(req.query).forEach(function(key) {
        query.select(key, req.query[key]);
    });

    // this was the way I was first handling the parameters, this works !!
    //if (req.query.username) query.where('username', req.query.username);
    //if (req.query.email) query.where('email', req.query.email);

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

});

These are the problems I'm struggling with:

  • Why is it not iterating over a req.query object?
  • How can I say that the mongoose uses a wildcard (e.g. kyo *)

It would be nice if someone could help me :)

Hi

EDIT

The second problem will be resolved with $ where:

    if (req.query.username) {
        query.$where(function() {
            return this.username === req.query.username; // here we need a regex check
        });
    }

Thos not working ... Can someone give me a hint?

EDIT2:

Nothing succeeded with $ where ... but now I found

query.where('username').regex();

,

EDIT3:

: MongoDB "like" ? mongoosejs,

EDIT4:

if (req.query.username) {
            query.where('username').regex(new RegExp("\/"+req.query.username+"\/"));
}

. ...

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

    Object.keys(req.query).forEach(function(key) {
        query.where(key).regex(new RegExp(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);
    });

});

, (.select() not.where()).

.

req.query (, - ),

+1

All Articles