Gobliins
Gobliins

Reputation: 4026

Saving new Date() in MongoDB Collection

I try to store a date inside a mongodb collection:

const date = new Date();
const time = {
  date:  date,
  timestamp:  date.getTime(),
}
Collection.insert(time); // no schema

What is actually stored:

{ "_id" : "PmMCEANtvfBwNGApH", "date" : "2021-01-14T14:33:36.520Z", "timestamp" : 1610634816 }

What i would expect:

{ "_id" : "PmMCEANtvfBwNGApH", "date" : " ISODate("2021-01-14T14:33:36.520Z"), "timestamp" : 1610634816 }

What do i have to do, to achieve the second?

Upvotes: -1

Views: 97

Answers (2)

Mohammad Yaser Ahmadi
Mohammad Yaser Ahmadi

Reputation: 5051

your code is correct because I runned and show result if you use new Date() for a field, the type is Date definitely like bellow photo test other things, maybe type is correct in your db, but change when you fetch data result,

Upvotes: 0

Syed Mohib Uddin
Syed Mohib Uddin

Reputation: 716

Try this see if it works.

const date = new Date();
const fullDate = date.getFullYear().toString() +'-'+ (date.getMonth() + 1).toString() + '-' + date.getDate().toString();
console.log(new Date(fullDate));

Upvotes: 0

Related Questions