Search code examples
node.jsexpressmongoosemiddleware

Does the middleware of mongoose also refer to the middleware of express?


I'm just trying to get a grasp of what middleware refers too. At first I thought it was functions used in the framework express. Although now I'm getting a sense that they simply just refer to functions that get in the middle between asynchronous functions.

I know it's common to see next() get used to move from one middleware to the next. Both express and mongoose have the next() call with similar names. I'm concerned as I don't see mongoose or express refer to each other in their documentation. So this leaves me to believe the context of their middleware is just for themselves.

http://mongoosejs.com/docs/middleware.html
http://expressjs.com/en/resources/middleware.html

When combining express with mongoose are all the middlewares lined up together/concatenated or is it separate?

e.g. together/concatenated
- calling next() on mongoose will also trigger expresses middleware function

e.g. Separate
- mongoose just has it's middleware next() just move for pre/post hooks
- express also just has it's middleware next() just move towards it's supported middleware functions


Solution

  • Short answer: they're separate.

    Longer answer: By convention, most middleware stacks implement some kind of next function to call in order to proceed down the stack and call each middleware function in turn.

    It's a matter of scope. Express and Mongoose both have their own independent middleware stacks, so what the next function does depends on where it gets called. As a general rule of thumb, every function-- including the anonymous functions used for callbacks that accept a next parameter-- have their own scope.

    Consider the following really brief example of differently scoped, but otherwise identical parameter names:

    function doSomething(arg) {
        console.log(arg)
    
        function doSomethingElse(arg) {
            console.log(arg);
        }
    
        doSomethingElse('different');
    }
    
    doSomething('original');
    // Outputs
    // > 'original'
    // > 'different
    

    Even though doSomething and doSomethingElse both have a parameter called arg, the value logged to the console by doSomethingElse is the value actually passed to that function-- the value of arg as scoped to the function it was called in, not the scope surrounding it.

    This is true for Mongoose middleware applied within Express middleware (or vice-versa): they just happen to share a similar, conventional parameter name.

    As a learning experiment, you should deviate from conventions for a moment (but not forever; conventions exist for a reason!) to name your Express and your Mongoose next parameters something else in a single file-- expressNext and mongooseNext, perhaps-- to help differentiate them in your mind.