I am using Node.js mongodb. I have a model like this
const calendarSchema = new Schema ({
title: String,
start: String, //start date
end: String, // end date
endDate: String,
sessionsRan: Number,
_user: {type: Schema.Types.ObjectId, ref: 'User' },
created: {
type: Date,
default: Date.now
},
})
What is the best way to query mongodb for this? I need to find documents where date < today and isActive: true.
I am currently doing this but not sure how implement a date search
const calendar = await Calendar.find({isActive: "active"})
CodePudding user response:
With $lt mongodb operator, you can query against the date field alongside isActive
field.
{start:{$lt: new Date().toISOString()}, isActive: true}
Here's a live demo
Note:
- Ensure your dates are saved as ISOString
- Your schema for dates should be constructed with
new Date()
object rather than a String.