sir_thursday sir_thursday - 5 months ago 31
Node.js Question

Better way to write this mongoose query string?

exports.all = function(req, res) {

if(!req.query.questionid) {
Answer.find().sort('-created').populate('creator', 'username').exec(function(err, answers) {
if (err) {
res.json(500, err);
} else {
res.json(answers);
}
});
} else {
Answer.find().sort('-created').where('questionid', req.query.questionid).populate('creator', 'username').exec(function(err, answers) {
if (err) {
res.json(500, err);
} else {
res.json(answers);
}
});
}
};


I think it's pretty clear what I'm trying to do- if a query parameter is provided, I want to query with the
where
filter, and if not, then I don't. There has got to be a better way to write this...

Answer

You can break apart your call chain a bit so that you can include only the parts you need:

exports.all = function(req, res) {

  var query = Answer.find().sort('-created').populate('creator', 'username');

  if(req.query.questionid) {
    query = query.where('questionid', req.query.questionid);
  }

  query.exec(function(err, answers) {
    if (err) {
      res.json(500, err);
    } else {
      res.json(answers);
    }
  });
};