Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Node.js - Requiring mongoose here and there causes redundancy?

Node.js - Requiring mongoose here and there causes redundancy?


I have the following Node.js directory structure.


In app.js, there's a line likes this mongoose.connect('mongodb://localhost/' + config.DB_NAME);. In schema.js:

var mongoose = require('mongoose')
    , Schema = mongoose.Schema
    , ObjectId = Schema.ObjectId;

var PostSchema = new Schema({
    title: String
    , author: String
    , body: String
    , creataAt: { 
        type: Date
        , default:

// other schemas goes here

module.exports.PostSchema = PostSchema;

In post.js:

var mongoose = require('mongoose')
    , PostSchema = require('./schemas').PostSchema
    , PostModel = mongoose.model('Post', PostSchema);

module.exports = PostModel;

And in index.js, there might be a line likes this: var PostModel = require('../models/post');. All files mentioned above require mongoose. The purpose of schemas.js is for helping programmers to grasp the schema of the database in a single file. However, I wonder if this implement causes redundancy and cause more overhead, for I require mongoose here and there. Should I pass it as an argument around?

Problem courtesy of: Trantor Liu


If you're only worried about performance, you need not be. As per


Modules are cached after the first time they are loaded. This means (among other things) that every call to require('foo') will get exactly the same object returned, if it would resolve to the same file.

Multiple calls to require('foo') may not cause the module code to be executed multiple times. This is an important feature. With it, "partially done" objects can be returned, thus allowing transitive dependencies to be loaded even when they would cause cycles.

If you want to have a module execute code multiple times, then export a function, and call that function.

So, you're not actually requiring Mongoose each time; rather, each time after the first, the cached Mongoose module is returned.

Solution courtesy of: Michelle Tilley


View additional discussion.

This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Node.js - Requiring mongoose here and there causes redundancy?


Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription