Mohammad
Mohammad

Reputation: 153

How to compare Dates in MongoDB (NodeJS + mongoose)?

I have some data in MongoDB and I want to Compare dates that are stored in it to be between 2 dates. the problem is it always returns null when I use $gte or $lte in queries.

Schema:

const SettingSchema = new Schema({
advertisment: [
    {
        name: {
            type: String,
            required: true
        }
        ,
        fromdate: {
            type: Date,
            default: Date.now()
        }
        ,
        todate: {
            type: Date
        }
        ,
        active:{
            type:Boolean
        }
    }
]});

Sample Data:

{
"advertisment": [
    {
        "fromdate": "2010-06-29T06:53:32.643Z",
        "_id": "5d170b634ebf4d1848efbe9a",
        "name": "ads1",
        "todate": "2030-06-29T09:38:32.643Z",
        "active": true
    },
    {
        "fromdate": "2010-06-29T06:53:32.643Z",
        "_id": "5d170baae38bc832c4d89d9a",
        "name": "ads2",
        "todate": "2030-06-29T09:38:32.643Z",
        "active": true
    }
]
}

Query :

let currentDate = new Date();

Setting.findOne(
    {
        "advertisment.active": true,
        "advertisment.fromdate": { $gte: currentDate },
        "advertisment.todate": { $lte: currentDate },
    },
    'advertisment')
    .then(data =>
    {
        console.log(data);
    })
    .catch(err => console.log(err))

how to compare these dates in MongoDB (mongoose)?

Upvotes: 12

Views: 18983

Answers (3)

NMI
NMI

Reputation: 528

actually you can simply compare using new Date() without convert it to ISODate as mongodb does. It seems that you have to switch your fromdate's $gte to $lte and todate's $lte to $gte, because $lte means your target/docs date field need to be earlier or equal than your specified date.

Upvotes: 1

Shivam Tripathi
Shivam Tripathi

Reputation: 445

You can check the type mongo saves by default easily. Go to the mongo shell, and type in Date(). It's essentially new Date().toString() in nodejs. If you type in new Date() you will get ISO Date string. Similarly, Date.now() would give timestamp.

Date.now() always gives present timestamp in epoch seconds (UNIX time) irrespective of params passed to it. Mismatch in types causes the failure when using comparison operators.

Depending upon what type you are storing, try using new Date().toISOString(), or new Date().toString() or Date.now(). The sample data you provided looks like it is ISO date string.

Upvotes: 4

Ravi Shankar Bharti
Ravi Shankar Bharti

Reputation: 9268

Use

new Date().toISOString()

instead of

new Date()

Try :

let currentDate = new Date().toISOString();

Setting.findOne(
    {
        "advertisment.active": true,
        "advertisment.fromdate": { $gte: currentDate },
        "advertisment.todate": { $lte: currentDate },
    },
    'advertisment')
    .then(data =>
    {
        console.log(data);
    })
    .catch(err => console.log(err))

Upvotes: 8

Related Questions