Errol Fitzgerald
Errol Fitzgerald

Reputation: 3008

Conditional Mongoose Query

I have a query that I want to run with a where case, only if a variable is false. This is what I'm doing now, but it's not optimal. Is there a way to do this with one query?

if (user) {
    models.Interviews.find({}).exec(function (err, interviews) {
        // stuff
    });
} else {
    models.Interviews.find({}).where('group').equals(group_id).where('disabled').equals(false).exec(function (err, interviews) {
        // stuff
    });         
}

Upvotes: 2

Views: 1678

Answers (2)

JohnnyHK
JohnnyHK

Reputation: 311835

If by 'not optimal' you're referring to needing to duplicate the 'stuff' code without a function, you can build up your Query object in steps like this:

var query = models.Interviews.find({});
if (!user) {
    query = query.where('group').equals(group_id).where('disabled').equals(false);
}
query.exec(function (err, interviews) {
    // stuff
});

Upvotes: 7

Thilo
Thilo

Reputation: 262464

Why is this not optimal? How would a single (more complicated) query be better?

What is not so nice is the duplicated "stuff", but you can easily fix that:

var stuff = function(err, interviews) {
    // stuff
 };

if (user) {
  models.Interviews.find({}).exec(stuff);
} else {
  models.Interviews.find({})
    .where('group').equals(group_id).where('disabled').equals(false)
    .exec(stuff);
}

or

var query = models.Interviews.find({});
if (!user){
   query = query.where('group').equals(group_id)
                .where('disabled').equals(false);
}
query.exec(function(err, interviews) {
    // stuff
 });

Upvotes: 1

Related Questions