Friday 5 May 2017

How to return an error in a mongoose query method?

I am just getting started with mongoose query methods they are really cool. I made a query method for knowing the ownership of an object. If yes it is his own, then the value of the object will be displayed else it should do an error like returning some error instead of something else.

someSchema.query.isOwner = function(user) {
    if (user.admin)
        return this;
    /* I know this will not work please suggesta solution for this too */
    else if (user._id === iShouldbeAbleToAccessTheObjectHere._id)
        return this;
    else
        // Put this into the error of exec
        return new Error('Permission denied!');
};

// This is how I'll use it
SomeModel
    .findById(someId)
    .isOwner(currentUser)
    .exec((err, result) => {
      if (err)
        res.json({ error : err });
      res.json({ data : result });
    });



via John foo

No comments:

Post a Comment