简体   繁体   中英

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM