13

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 })

3 Answers 3

24

Use $gte like this :

Example.find({
    validUntil: {
        $gte: new Date(2016,09,30)
    }
})
Sign up to request clarification or add additional context in comments.

2 Comments

@chovy Date.now() returns a number and not a Date object. If you want to compare with the current Date, then simply use new Date().
@robere2 when using new Date() it still throws me error for casting.
12

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 })

Comments

3

get all created account 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) )

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.