Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7932201
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 3, 20262026-06-03T20:56:40+00:00 2026-06-03T20:56:40+00:00

This is a pure best practice question. I am pretty new to Node and

  • 0

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.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-03T20:56:43+00:00Added an answer on June 3, 2026 at 8:56 pm

    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.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

This is not a pure programming question, however it impacts the performance of programs
I have a pure C++ application developed using VC 6.0. I would like this
I've been reading up on this Law of Demeter thing, and it (and pure
This problem has been bugging me since forever. I have an array and in
I have given up doing this in pure js. And I can't find the
I want to use this pure HTML/CSS template for my ASP.NET website: http://sub3.tanguay.de I
I make this post because a script of pure javascript tooltips, no jquery and
Is there a pure .net way to do this reliably? The solutions I keep
I need multemethod dispatch with Moose objects. I'm doing this with Class::Multimethods::Pure . I
This more of a style question, rather than a how to. So I've got

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.