Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting date value from nodejs to mongodb

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.

like image 858
Abhijeet Srivastava Avatar asked Dec 13 '16 09:12

Abhijeet Srivastava


People also ask

How manually insert data in MongoDB?

The insert() Method To insert data into MongoDB collection, you need to use MongoDB's insert() or save() method.

How do I set date in MongoDB?

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.


2 Answers

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());
like image 66
Dennington-bear Avatar answered Sep 23 '22 08:09

Dennington-bear


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

like image 28
Yi Xiang Chong Avatar answered Sep 22 '22 08:09

Yi Xiang Chong