问题与mongoose时间戳记和时代转换为date()
我有一个Mongoose模式与timestamp
选项设置为true。
schema = new mongoose.Schema({ ... }, { timestamps: true });
现在我有一个使用System.currentTimeMillis()
获取时间戳的Android应用程序,它工作得很好,并且自UNIX纪元时间以来可以提供毫秒数。
我将这些数据发送到我的Node.js / Express服务器上,这个服务器会花费时间,只返回在特定date之后创build的文档。
// get all docs router.get('/api/seekers', function(req, res) { Seeker.find({createdAt:{ $gt: new Date(req.query.timestamp) }}, function(err, seekers) { if(err) res.send(err); else res.json(seekers); }); });
所以我发送https://api_url.com/api/seekers?timestamp=1479431351762
作为一个请求到服务器。
现在发生了一些事情:
-
我以毫秒为单位发送值,并得到这个错误
{"message":"Cast to date failed for value \"Invalid Date\" at path \"updatedAt\"","name":"CastError","kind":"date","value":null,"path":"updatedAt"}
经过一点调查,事实certificate,你需要秒通过
Date()
。 所以, -
我把值除以1000得到秒(
req.query.timestamp/1000
)。 现在我没有收到错误,但查询约束不起作用。 我从开始的时候就获得了所有的价值。 -
我移到了Mongo shell来检查问题是否依然存在,事实certificate这不是问题,因为我可以将毫秒值传递给Mongo的Date:
> new Date(1479431351762) ISODate("2016-11-18T01:09:11.762Z")
但是,如果我尝试将第二个值传递给
Date()
,事实certificate它实际上是发送给我的开始时间:> new Date(1479431351) ISODate("1970-01-18T02:57:11.351Z")
我无法弄清楚,我能做些什么服务器请求和mongoose正确处理时间戳和查询我的数据库?
任何有相同问题的stream浪者,可能已经错过了chridam的评论,你只需要在parsing之前将传递的时间戳转换为int
。 这工作:
new Date(parseInt(req.query.timestamp))