18

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.

Dennington-bear
  • 1,732
  • 4
  • 18
  • 44
Abhijeet Srivastava
  • 311
  • 1
  • 5
  • 15

3 Answers3

8

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());
Dennington-bear
  • 1,732
  • 4
  • 18
  • 44
  • 2
    Thanks @Dennington-bear for your input but my ask was opposite. I want date in DB as ISODate(date). Issue here is if I have array of object for ex- [{date: new Date()}, { -- }, { -- }] and I want to pass this array directly to the insertMany query then how can I get ISODate(date) – Abhijeet Srivastava Dec 13 '16 at 17:06
  • 5
    `new Date(Date.now()).toISOString()` this is still going as string – Ajit Singh May 02 '19 at 11:52
  • 1
    I believe this is incorrect and made the same mistake which caused errors in my existing database. Do not use new Date().toISOString when inserting into MongoDB database (instead just use new Date()) because using .toISOString will make .find() operators or $gte operators on the database fail – – Yi Xiang Chong Apr 15 '20 at 09:42
  • 1
    I believe this is incorrect and made the same mistake which caused errors in my existing database. Do **not** use ```new Date().toISOString()``` when inserting into MongoDB database (instead just use ```new Date()```) because MongDB does the conversion for you and using .toISOString will make .find() operators or $gte operators on the database fail – Yi Xiang Chong Apr 15 '20 at 11:22
7

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

Liam
  • 27,717
  • 28
  • 128
  • 190
Yi Xiang Chong
  • 744
  • 11
  • 9
  • This is the correct answer. Be aware of the rules around [string parsing to dates though](https://stackoverflow.com/questions/5619202/converting-a-string-to-a-date-in-javascript). Ideally your date string should be in a [ISO 8601 format](https://en.wikipedia.org/wiki/ISO_8601) – Liam Jan 29 '21 at 16:52
2

To save as a Date in MongoDB I did this.

items = [{
    serverName: 'myServer',
    checkDate: '2016-12-13T06:55:24.698Z',
  }]

addMany(items) {

    // to tell mongodb to save as a date
    items.forEach((obj) => {
      obj.checkDate = new Date(obj.checkDate);
    });

    return this.dbClient
      .then(db => db
        .collection(this.collection)
        .insertMany(items));
  }
Hugues Gauthier
  • 639
  • 8
  • 18