In my mongodb database I have a collection named Bookings in the model there is a field named periodFrom (representing a date in a string) which is of type String.
I need to find the documents in this collection which have a periodFrom greater than today's date. I tried using virtuals but it did not work.
Here is an example of a few documents in my Bookings collection :
{"name": "A", "periodFrom": "29.04.2022 10:00", "place": "Tokyo"},
{"name": "B", "periodFrom": "30.06.2022 10:00", "place": "Paris"}
{"name": "C", "periodFrom": "28.04.2022 10:00", "place": "Berlin"},
{"name": "D", "periodFrom": "01.07.2022 10:00", "place": "London"}
My bookingSchema :
const bookingSchema = new Schema({
name: {type: String},
periodFrom: {type: String},
place: {type: String}
})
I tried virtuals by adding at the end of my model booking.js
bookingSchema.virtual('periodFromDate').get(function () {
return new Date(this.periodFrom.split(' ')[0].split('.')[2].toString() + "-" + this.periodFrom.split(' ')[0].split('.')[1].toString() + "-" + this.periodFrom.split(' ')[0].split('.')[0].toString())
const Booking = mongoose.model("Booking", bookingSchema);
});
I tried the request by doing the following :
let allCrew = await Booking.find({ periodFromDate: { $gte: Date.now() } })
I also tried this way but it was not working either:
let allCrew = await Booking.find({ periodFrom: { $gte: '2022.07.01 00:00' } })
So any ideas how I could find the documents that have a periodFrom greater than today's date if periodFrom is a string of a date in mongoose?