简体   繁体   English

在 MongoDB 集合中保存新的 Date()

[英]Saving new Date() in MongoDB Collection

I try to store a date inside a mongodb collection:我尝试将日期存储在 mongodb 集合中:

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?我必须做什么才能实现第二个目标?

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));

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你的代码是正确的,因为如果你对一个字段使用new Date() ,我运行并显示结果,类型肯定是日期,就像下面的照片测试其他东西,也许你的数据库中的类型是正确的,但是当你获取数据时改变结果 , ,

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM