Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper Handling of fetch errors for Mongoose?

This is a pure best practice question. I am pretty new to Node and Mongoose. I absolutely love the technology and have been cranking away on a project to build a JSON-backed API for an app that I'm building.

I am finding that I am continuously repeating code when I fetch objects from my database. For example:

Playlist.findById(req.params.id, function(err,playlist){
  if (err)
    return res.json({error: "Error fetching playlist"});
  else if (!playlist)
    return res.json({error: "Error finding the playlist"});

  //Actual code being performed on the playlist that I'm fetching
});

The error handling at the top of the function call is annoying because I have to repeat that code for every call to the database... or so I think.

I thought about using a callback like:

var fetchCallback = function(err,objOrDoc,callback){
  //Handle the error messages
  callback(objOrDoc);
};

However, this approach would mess up my sequential flow since I would have to define the callback function before I performed the fetch. So, if I had a lot of database queries chained together, I would have to place the callbacks in reverse order, which is far from ideal in a clean-coding perspective.

I'm wondering if anyone has run into this issue and has any best practices for cutting down on the repetition.

I'm also using the express framework, so if there's a helpful way to handle it in express, I'd be interested to know, too.

like image 849
Michael D. Avatar asked May 06 '12 16:05

Michael D.


1 Answers

There are a couple interesting approaches you could try here.

At the most simple, you could simply have a function that loads up an object and handles the output in an error condition.

fetchResource = function(model, req, res, callback) {
  model.findById(req.params.id, function(err, resource) {
    if (err)
      return res.json({error: "Error fetching " + model.toString()});
    else if (!playlist)
      return res.json({error: "Error finding the " + model.toString()});

    callback(resource);
  });
};

app.on('/playlists/1', function(req, res) {
  fetchResource(Playlist, req, res, function(playlist) {
    // code to deal with playlist.
  });
});

That's still quite a bit of duplication, so I might try to move this out into a middleware.

Route Middleware

Routes may utilize route-specific middleware by passing one or more additional callbacks (or arrays) to the method. This feature is extremely useful for restricting access, loading data used by the route etc.

Now I haven't tested this and it's a bit hand-wavey (read: pseudocode), but I think it should serve as a decent example.

// assuming a URL of '/playlist/5' or '/user/10/edit', etc.

function loadResource(model) {
  return function(req, res, next) {
    model.findById(req.params.id, function(err, resource) {
      if (err)
        return res.json({error: "Error fetching " + model.toString()});
      else if (!resource)
        return res.json({error: "Error finding the " + model.toString()});

      req.resource = resource;
      next();
    });
  }
}

app.get('/playlist/:id', loadResource(Playlist), function(req, res) {
  var playlist = req.resource;
  ...
});

app.get('/user/:id', loadResource(User), function(req, res) {
  var user = req.resource;
  ...
});

The express source contains a pretty good example of this pattern, and the middleware section in the docs (specifically under 'Route Middleware') details it further.

like image 115
Michelle Tilley Avatar answered Sep 26 '22 17:09

Michelle Tilley