Node.js 从mongoDB中输入条目到现在已经有多少天了?

Node.js 从mongoDB中输入条目到现在已经有多少天了?,node.js,express,mongoose,Node.js,Express,Mongoose,我有这个猫鼬模型 const GoalSchema = new Schema({ . . . . Date: { type: Date, default: Date.now } . . . . }); 我正在试图弄清楚这个对象创建以来有多长时间了,我尝试了以下方法: const oneDay = 1000 * 60 * 60 * 24 ; const temp = new Date(

我有这个猫鼬模型

const GoalSchema = new Schema({
    .
    .
    .
    .
    Date: {
        type: Date,
        default: Date.now
    }
    .
    .
    .
    .
});
我正在试图弄清楚这个对象创建以来有多长时间了,我尝试了以下方法:

const oneDay = 1000 * 60 * 60 * 24 ;
const temp = new Date();
const diff = (temp - goal.Date.getTime());
diff /= oneDay;

这里的目标是我从猫鼬那里收到的目标对象。你能帮我算出已经过去了多少天吗?

使用Mongoose时间戳功能

const GoalSchema = new Schema({
    yourFields: String
}, {timestamps: true});
这将在MongoDB文档上自动创建createdAt和updatedAt字段

然后得到日期之间的差异。使用以下代码

let createdDate = new Date(doc.createdAt);
let currentDate = new Date();
let timeDif = Math.abs(createdDate.getTime() - currentDate.getTime());

let differentDays = Math.ceil(timeDifference / (1000 * 3600 * 24));
或者你可以用


我认为您不应该在数据库中提供名称
Date
。我总是使用as
创建、在更新等等。在你得到你的
goal
对象后,你的
goal.Date
将是
timestamp
而不是JS
Date
对象,因此如果你不按原样施放,就不会有
getTime
函数。要找到差异,只需使用此insead
const diff=Date.now()-goal.Date希望如此helps@Halil当我在console.log diff.我不确定自己是否做错了什么时,我得到了NaNconst diff=(Date.now-goal.Date);控制台日志(diff)`
Date.now()
将其称为函数:)您能建议一种正确的方法来计算对象创建以来的天数吗?@KenAdams编辑了答案,其中包括日期差的计算。
let createdDate = moment(doc.createdAt);
let currentDate = moment()
createdDate.diff(currentDate, 'days')