Mongoose时间戳和epoch转换为Date()的问题

时间:2016-11-18 14:50:44

标签: android node.js mongodb date mongoose

我有一个Mongoose架构,timestamp选项设置为true。

schema = new mongoose.Schema({
    ...
},
{ timestamps: true });

现在我有一个Android应用程序,它使用System.currentTimeMillis()来获取时间戳,这个应用程序运行良好,并且在UNIX纪元时间之后给出了毫秒数。

我将这些数据发送到我的Node.js / Express服务器,该服务器花费时间并仅返回在该特定日期之后创建的文档。

// 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作为请求发送给服务器。

现在发生了一些事情:

  1. 我以毫秒为单位发送值并获得此错误

    {"message":"Cast to date failed for value \"Invalid Date\" at path \"updatedAt\"","name":"CastError","kind":"date","value":null,"path":"updatedAt"}

    经过一番调查后,发现你需要将秒数传递给Date()。所以,

  2. 我将值除以1000得到秒(req.query.timestamp/1000)。现在我没有收到错误,但查询约束无效。我从一开始就获得所有价值。

  3. 我转移到Mongo shell来检查问题是否仍然存在,结果是因为我可以将毫秒值传递给Mongo'日期:

    > new Date(1479431351762) ISODate("2016-11-18T01:09:11.762Z")

    但是,如果我尝试将第二个值传递给Date(),则事实证明实际上是将我发送到时间的开头:

    > new Date(1479431351) ISODate("1970-01-18T02:57:11.351Z")

  4. 我无法弄清楚这一点,我能做什么,所以服务器请求和猫鼬正确处理时间戳并查询我的数据库?

1 个答案:

答案 0 :(得分:2)

任何有同样问题的流浪者,可能错过了chridam的评论,你只需要在解析之前将传递的时间戳强制转换为int。这有效:

new Date(parseInt(req.query.timestamp))

相关问题