Search code examples
node.jsmongodbmongoskin

Mongo findOne access properties issue


Ok maybe i don't see it but this query looks fine to me:

db.bind('links');
db.links.findOne({ short_id: req.params.id }, function(err, link) {
    console.log(link["post_id"]); // I also tried console.log(link.post_id)
    res.jsonp(link);
});

But the error says: "TypeError: Cannot read property 'post_id' of null". Then i tried to remove that console.log, and i got the output on the browser, so link is not null it has some value, but why it's trowing and error when accessing it's properties, any ideas?


Solution

  • Ok so it was not a mongo issue after all, it was my routes... Because my route structure is like /, /:id?, and because of some reason the code was called twice, the first time it worked but the second time it was null.

    So all i had to do is to check if id exists:

    router.get('/:id?', function(req, res) {
      var id = req.params.id;
      if (!id) {
        next();
        return;
      }
      ...
    });