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

13,069

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.

Share:
13,069
justin
Author by

justin

Updated on June 30, 2022

Comments

  • justin
    justin almost 2 years

    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!

  • justin
    justin over 10 years
    ah, fantastic- I thought I had to use the helpers and wasn't sure how the "or" was implemented in conjunction with the original "find". I will try this when back in the office later today.