justin
justin

Reputation: 659

How do you utilize $and, $or, $exists in the same Mongoose.js query?

I need to query documents for an account that either has no expiration[expires] (does not exist) or the expiration date is after 2/2/14. To do so, my mongodb query is:

db.events.find({ _account: ObjectId("XXXX"), 
    $or: [
        {expires: {$gt: ISODate('2014-02-02')}}, 
        {expires: {$exists: false}}
    ]
});

I'm having trouble with the correct mongoose .or() .and() .exists() chaining, how would I convert this into Mongoose?

Thanks!

Upvotes: 4

Views: 14034

Answers (1)

Neil Lunn
Neil Lunn

Reputation: 151170

There should be nothing wrong with using the same syntax, more or less as in the shell. It's still javascript, just without the shell helpers.

Events.find({ _account: "XXXX", 
  $or: [
    {expires: {$gt: Date(2014,02,02)}},
    {expires: {$exists: false }}
}, function(err, events) {
    if (err) // TODO
    // do something with events
});

Alternately you are using other helpers to build the query:

var query = Events.find({ _account: "XXXX" });

query.or(
    {expires: {$gt: Date(2014,02,02)}},
    {expires: {$exists: false }}
);

query.exec(function(err, events) { 
   if (err) // TODO
   // do something with events
});

Or other combinations. These 'helpers' largely exist in drivers for syntax parity with other non-dynamic languages like Java. You can look for examples of QueryBuilder usage in Java if you prefer this way and can't find the node references. For mongoose there is the documentation for queries that is worth a look.

Dynamic languages have a more native approach to defining such object structures as used for queries etc. So most people prefer to use them.

Upvotes: 11

Related Questions