Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose or operator with Date

I am trying to write a query like:

var query = {
    userId: req.params.userId,
    isActive: true,
    'interval.start': {
        $lte: now
    },
    'interval.end': {
        $or: [
            { $gte: now },
            { $exists: false },
            { $eq: null } 
        ]
    }
};

What I am trying to achieve is I want to find columns that should fit to these conditions:

  • interval.end Date should be greater than now.
  • OR end date shouldn't exist
  • OR it should exist to null.

I am getting: Can't use $or with Date. error.

Thank you.

like image 755
Yagiz Avatar asked Jan 12 '16 21:01

Yagiz


People also ask

How to store a Date in mongoose?

Here's how you declare a path of type Date with a Mongoose schema: const mongoose = require('mongoose'); const userSchema = new mongoose. Schema({ name: String, // `lastActiveAt` is a date lastActiveAt: Date }); const User = mongoose.

What is date format in mongoose?

The Date SchemaType configures MongoDB to store the date as a BSON native Date object in our database. An example is shown below: ISODate("1990-01-01T23:00:00Z") The example above shows how Date is stored in a MongoDB database.

How does a mongoose save time?

Timestamps save the current time of the document created and also when it was updated in form of a Date by turning it true. When set to true, the mongoose creates two fields as follows: createdAt: Date representing when the document was created. updatedAt: Date representing when this document was last updated.

How does MongoDB store time only?

Basically you have two options: Save time in type: String. Save date time in type: Date.


1 Answers

As far as I know you can't nest $or inside some specific field. The $or operator takes an array of expressions.

Try the following query:

var query = {
    userId: req.params.userId,
    isActive: true,
    'interval.start': {
        $lte: now
    },
    $or: [
        {'interval.end': {$gte: now} },
        {'interval.end': {$exists: false} },
        {'interval.end': null } 
    ]
};
like image 145
Volodymyr Synytskyi Avatar answered Oct 22 '22 04:10

Volodymyr Synytskyi