sir_thursday
sir_thursday

Reputation: 5419

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...

Upvotes: 0

Views: 808

Answers (2)

Diego Haz
Diego Haz

Reputation: 939

You can achieve a very nice approach by using querymen.

var querymen = require('querymen')

app.use('/', querymen.middleware({
  questionid: mongoose.Types.ObjectId,
  sort: '-created'
}))

app.get('/', function(req, res) {
  console.log(req.querymen) // {query: {questionid: <ObjectId>}, cursor: {sort: {created: -1}}}
  Answer.find(req.querymen.query, null, req.querymen.cursor)
    .populate('creator', 'username')
    .exec(function(err, answers) {
      if (err) {
        res.json(500, err);
      } else {
        res.json(answers);
      }
    })
})

Upvotes: 2

JohnnyHK
JohnnyHK

Reputation: 312035

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);
    }
  });
};

Upvotes: 1

Related Questions