Note that there are some explanatory texts on larger screens.

plurals
  1. POExpressjs: Search query api
    text
    copied!<p>I want to search through my user repository with a query string.</p> <p>This should return all users with a similar username "kyogron" and similar email "kyogron@gmail"</p> <pre><code>GET localhost:3000/users?username=kyogron&amp;email=kyogron@gmail.com </code></pre> <p>This should return all users:</p> <pre><code>GET localhost:3000/users </code></pre> <p>I already managed to handle the routing parameters but I am stuck at optimizing it:</p> <pre><code>app.get('/users', function(req, res) { // creates a mongoosejs query object var query = User.find({}); // to understand how expressjs handles queries: // ?username=kyogron&amp;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); }); }); </code></pre> <p>These are the problems I am fighting with:</p> <ol> <li>Why doesn't iterating the req.query object work?</li> <li>How do I say mongoose to use a wildcard (e.g. kyo*)</li> </ol> <p>Would be nice if somebody could help me out :)</p> <p>Regards</p> <p><strong>EDIT</strong>:</p> <p>The second issue would be solvable with $where:</p> <pre><code> if (req.query.username) { query.$where(function() { return this.username === req.query.username; // here we need a regex check }); } </code></pre> <p>Thos doesn't work... Could somebody give me a hint?</p> <p><strong>EDIT2:</strong></p> <p>Didn't managed anything with $where... however I now found </p> <pre><code>query.where('username').regex(); </code></pre> <p>I just have to look for a searching regex which looks for similar words</p> <p><strong>EDIT3:</strong></p> <p>I found this thread: <a href="https://stackoverflow.com/questions/3305561/how-to-query-mongodb-with-like">How to query MongoDB with &quot;like&quot;?</a> I ask in the mongoosejs group how I could do this with mongoose</p> <p><strong>EDIT4:</strong></p> <pre><code>if (req.query.username) { query.where('username').regex(new RegExp("\/"+req.query.username+"\/")); } </code></pre> <p>I nearly got it. Just have to fix this stupid regex...</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload