Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 303
justin Avatar asked Dec 20 '22 18:12

justin


1 Answers

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.

like image 182
Neil Lunn Avatar answered Jan 15 '23 09:01

Neil Lunn