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/users?username=kyogron&[email protected]
This should return all users:
GET localhost:3000/users
I already managed to handle the routing parameters but I am stuck at optimizing it:
app.get('/users', function(req, res) {
// creates a mongoosejs query object
var query = User.find({});
// to understand how expressjs handles queries:
// ?username=kyogron&[email protected]
// { username: "kyogron", email: "[email protected]" }
//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 am fighting with:
Would be nice if somebody could help me out :)
Regards
EDIT:
The second issue would be solvable with $where:
if (req.query.username) {
query.$where(function() {
return this.username === req.query.username; // here we need a regex check
});
}
Thos doesn't work... Could somebody give me a hint?
EDIT2:
Didn't managed anything with $where... however I now found
query.where('username').regex();
I just have to look for a searching regex which looks for similar words
EDIT3:
I found this thread: How to query MongoDB with "like"? I ask in the mongoosejs group how I could do this with mongoose
EDIT4:
if (req.query.username) {
query.where('username').regex(new RegExp("\/"+req.query.username+"\/"));
}
I nearly got it. Just have to fix this stupid regex...
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);
});
});
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With