I use Mongoose in my project and in one of the schemas I use Date field, like this:
reservationDay: {
type: Date,
default: Date.now
}
Convert date to MongoDB ISODate format in JavaScript using Moment JS
MongoDB uses ISODate as their primary date type. If you want to insert a date object into a MongoDB collection, you can use the Date() shell method.
You can specify a particular date by passing an ISO-8601 date string with a year within the inclusive range 0 through 9999 to the new Date() constructor or the ISODate() function. These functions accept the following formats:
"<YYYY-mm-dd>"
) returns the ISODate with the specified date."<YYYY-mm-ddTHH:MM:ss>"
) specifies the datetime in the client’s local timezone and returns the ISODate with the specified datetime in UTC."<YYYY-mm-ddTHH:MM:ssZ>"
) specifies the datetime in UTC and returns the ISODate with the specified datetime in UTC.If you are writing code in JavaScript and if you want to pass a JavaScript date object and use it with MongoDB client, the first thing you do is convert JavaScript date to MongoDB date format (ISODate). Here’s how you do it.
var today = moment(new Date()).format('YYYY-MM-DD[T00:00:00.000Z]');
console.log("Next day -- " + (reqDate.getDate() + 1))
var d = new Date();
d.setDate(reqDate.getDate() + 1);
var tomorrow = moment(d).format('YYYY-MM-DD[T00:00:00.000Z]');
You can pass today and tomorrow object to MongoDB queries with new Date() shell method.
MongoClient.connect(con, function (err, db) {
if (err) throw err
db.collection('orders').find({ "order_id": store_id, "orderDate": {
"$gte": new Date(today), "$lt": new Date(tomorrow)}
}).toArray(function (err, result) {
console.log(result);
if (err) throw err
res.send(result);
})
})
I would like to update one point from my mistake.
check if you have missed leading zero for a single digit time.
"2017-01-01T8:00:00" is invalid and will give the mentioned error.
"2017-01-01T08:00:00" is valid
"20/11/2014 04:11"
is an invalid ISODate format. Somewhere you are converting reservationDate into a string of an invalid format. You need to convert it to a valid ISODate format (month before day):
new Date("11/20/2014 04:11") // Thu Nov 20 2014 04:11:00 GMT+0100 (CET)
new Date("2014/11/20 04:11") // Thu Nov 20 2014 04:11:00 GMT+0100 (CET)
new Date("20/11/2014 04:11") // Invalid Date
for easy manipulation of date formats, I'd recommend using moment.js