Search code examples
javascriptnode.jsmongodbmongodb-querynode-mongodb-native

MongoDB Native Node.js issue


I've been running into an issue when creating a Node REST API that reads from a MongoDB db (I'm using Mongodb-native, not Mongoose in this case). I'm trying to query for all results after a given timestamp that I am reading from a local file. I then get the timestamp of the upmost event and save this into the file (the goal is that this method should return the latest events from the last query, if that makes sense).

This is my code so far:

router.get("/latestevent", function(req, res, next) {
    db.collection("events", function(err, collection){
            var contents = new Date(fs2.readFileSync('latesttimeevent','utf8')).toISOString();
            console.log("Newest previous date is: " + contents);
            var date = String(contents);
            collection.find({event: {$regex: '00FF0004'},eventtime: {'$gte':new Date(date)}}).sort({$natural:-1}).limit(10).toArray(function(err, data)
            {
                    fs.writeFile("latesttimeevent",data[0].eventtime, function(err)
                    {
                            if(err)
                            {
                                    return console.log(err);
                            }
                            console.log("Cell File was saved");
                    });
                    res.json(data);
            })
    });
});

Console.log("Newest previous date is: " + contents) returns a date in this format: 2017-12-27T18:57:37.000Z. When I plug in that date to the function new Date(date) -> new Date("2017-12-27T18:57:37.000Z"), I am able to successfully get the information when making REST calls. However, the way it is right now, when trying to make a GET call using Postman, it just buffers (sometimes it will work on the first attempt, but then it buffers after).

Any idea on what I'm doing wrong here? I tried messing around with the new Date(...) a lot with different string options, removing new Date, adding toISOString(), etc. but to no success.

Thanks!


Solution

  • I think the point is on client side, not server. I'm not familiar with Postman, but my point is that you need to set Cache control (for your client Get request header) to no-cache, ex:

    Cache-Control: no-cache, no-store, must-revalidate
    

    Also you can try set max-age cache header param as well,

    max-age=0
    

    (details: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control)