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) {
var query = User.find({});
Object.keys(req.query).forEach(function(key) {
query.select(key, req.query[key]);
});
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;
});
}
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+"\/"));
}
. ...