title: How to write Mongoose Queries with optional express query-params?
body: <p>I am building a REST API on top of Express 4. For a path lets say <code>GET /api/users</code> I want to query my users collection accordingly to <strong><em>optional</em></strong>  queryParams.</p>
  
  <p>So a call to the API could look like this <code>host:port/api/users?city=Berlin</code></p>
  
  <p>In this case <code>name</code> is omitted and doesn't influence the query, whereas <code>city</code> has to match.</p>
  
  <p>I managed to do this with the following hack. Is there a better way than that?</p>
  
  <pre><code>Users.statics.customFilter = function(qP){
      return this.find({
          $and: [
              {$or: [{undefined: {$eq: qP.city}}, {'city': qP.city}]},
              {$or: [{undefined: {$eq: qP.name}}, {'name': qP.name}]}
          ]
      });
  
  mongoose.model('User', Users);
  </code></pre>
  
  <p>I'm calling this static function from the mongoose schema like this...      </p>
  
  <pre><code>const User = mongoose.model('User');
  app.get('/api/users', (req, res) =&gt; {
          User.customFilter(req.query)
          .exec((err, results) =&gt; {
              if (err) return next(err);
              res.json(results);
          });
      });
  </code></pre>