I am trying inserting one date value from expressjs to mongodb. I am using mongodb native driver.
The issue is when I am using creating an object and inserting it using that variable , the date is inserted as string. Here is the sample-
var expenseTest = {date: new Date()};
database.collection('expensemaster').insert(expenseTest, function(err, r){
console.log("query executed");
});
Here the the value in DB-
{
"_id" : ObjectId("584f9b6e8c06a5717d10ee59"),
"date" : "2016-12-13T06:55:24.698Z",
}
But when I am inserting the object directly in the insert query its date is returning as ISODate(date).
Here is the sample-
database.collection('expensemaster').insert({date: new Date()}, function(err, r) {
console.log("query executed");
});
The value in db-
{
"_id" : ObjectId("584fba82566fc8787e75a7ed"),
"date" : ISODate("2016-12-13T09:08:18.441Z")
}
My question is - what if I have to use insertMany to insert array of object having date as one of the field.
How can I get date as ISODate(date) in the db.
The insert() Method To insert data into MongoDB collection, you need to use MongoDB's insert() or save() 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: new Date("<YYYY-mm-dd>") returns the ISODate with the specified date.
When you insert instead of calling
database.collection('expensemaster').insert({date: new Date()}, function(err, r) {
console.log("query executed");
});
use this :
database.collection('expensemaster').insert({date: new Date(Date.now()).toISOString()}, function(err, r) {
console.log("query executed");
});
This will create an iso date for you to insert. I use Date.now()
but you can insert whatever date you want there. Below is the console log of what the .toISOString
does
console.log(new Date(Date.now()).toISOString());
Use new Date()
when inserting into MongoDB database. Do not use new Date().toISOString()
when inserting into MongoDB database because MongoDB already does the conversion for you and using .toISOString()
will make .find()
operators or $gte
operators on the database fail
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With