Mongoose query by date

I want to query mongoDB with a document structure like this:

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

and he needs to return only valid documents, i.e. where validUntil is greater than the current time. This does not work, mongoose returns all documents:

var d = new Date();
var n = d.toISOString();
Example.find({ '$where': 'validUntil'>n })
+7
source share
3 answers

Use $gteas follows:

Example.find({
    validUntil: {
        $gte: new Date(2016,09,30)
    }
})
+13
source

If found today using impulses

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

Example.find({ validUntil: { '$gte': start, '$lte': end })
+2
source

get all created accounts today:

  let start = new Date(now.getFullYear(),now.getMonth(),now.getDate(),1,0,0);

  let end = new Date(now.getFullYear(),now.getMonth(),now.getDate()+1,0,59,59);

  let query = {createdAt: {$gte: start, $lt: end} };

  Account
  .find(query)
  .exec((err, accounts) => console.log(account) )
0
source

Source: https://habr.com/ru/post/1659349/


All Articles