简体   繁体   中英

Issue with Mongoose Timestamp and epoch conversion to Date()

I have a Mongoose schema with the timestamp option set as true.

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

Now I have an Android application that gets the timestamp using System.currentTimeMillis() which works all well and good and gives me number of milliseconds since UNIX epoch time.

I send this data across to my Node.js / Express server which takes the time and returns only documents created after that particular date.

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

So I send https://api_url.com/api/seekers?timestamp=1479431351762 as a request to the server.

Now a couple of things happen:

  1. I send the value in milliseconds and get this error

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

    After a little bit of investigation, it turns out you need to pass seconds to Date() . So,

  2. I divide the value by 1000 to get seconds ( req.query.timestamp/1000 ). Now I wasn't getting an error, but the query constraint was not working. I'm getting all values since the beginning of time.

  3. I moved over to the Mongo shell to check whether the issue persists, to which it turns out it doesn't since I can pass the millisecond value to Mongo's Date:

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

    But if I tried passing the second value to Date() , it turns out it actually was sending me to the beginning of time:

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

I'm unable to figure this out, what can I do so server request and mongoose correctly processes the timestamp and queries my db?

Any wanderers with the same issue, who might have missed chridam 's comment, you just need to cast the passed timestamp to int before parsing. This works:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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