Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose query by date

I want to query mongoDB with document structure like this:

var ExampleSchema = mongoose.Schema({
    createdAt: { type: Date, default: Date.now },
    validUntil: Date,
    name: String
});

and need it to return only valid documents, i.e. where validUntil is greater than current time. This doesn't work, mongoose returns all documents:

var d = new Date();
var n = d.toISOString();
Example.find({ '$where': 'validUntil'>n })
like image 459
mdakovac Avatar asked Oct 30 '16 18:10

mdakovac


2 Answers

Use $gte like this :

Example.find({
    validUntil: {
        $gte: new Date(2016,09,30)
    }
})
like image 135
Bertrand Martel Avatar answered Sep 19 '22 16:09

Bertrand Martel


If find in today, using momentjs

// start today
var start = moment().startOf('day');
// end today
var end = moment(today).endOf('day');

Example.find({ validUntil: { '$gte': start, '$lte': end })
like image 37
Tính Ngô Quang Avatar answered Sep 21 '22 16:09

Tính Ngô Quang