如果您插入startDate:moment(),这将保存moment 对象的内容......而不是您可能期望的Date 字段。
例如,在mongo shell 中:
> db.mycollection.insert({startDate:moment()})
WriteResult({ "nInserted" : 1 })
> db.mycollection.findOne()
{
"_id" : ObjectId("5401a7805a5b0e4e0bfe5170"),
"startDate" : {
"_isAMomentObject" : true,
"_i" : null,
"_f" : null,
"_l" : null,
"_strict" : null,
"_isUTC" : false,
"_pf" : {
"empty" : false,
"unusedTokens" : [ ],
"unusedInput" : [ ],
"overflow" : -2,
"charsLeftOver" : 0,
"nullInput" : false,
"invalidMonth" : null,
"invalidFormat" : false,
"userInvalidated" : false,
"iso" : false
},
"_d" : ISODate("2014-08-30T10:29:20.529Z")
}
}
在startDate._d 字段中保存了一个适当的Date,但我认为您真正想要做的是使用new Date() 构造函数在startDate 字段中保存一个值:
> db.mycollection.insert({startDate:new Date()})
WriteResult({ "nInserted" : 1 })
> doc = db.mycollection.findOne()
{
"_id" : ObjectId("5401a8fe5a5b0e4e0bfe5173"),
"startDate" : ISODate("2014-08-30T10:35:42.736Z")
}
现在您应该能够按预期执行日期数学:
> var now = moment();
// Diff in milliseconds (http://momentjs.com/docs/#/displaying/difference/)
> now.diff(doc.startDate)
6825