Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have the following Node.js directory structure.

|--app/
   |--app.js
   |--routers/
      |--index.js/
   |--models/
      |--schemas.js
      |--post.js

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: Date.now
    }
});

// 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?

like image 933
Trantor Liu Avatar asked Jun 28 '12 02:06

Trantor Liu


1 Answers

If you're only worried about performance, you need not be. As per http://nodejs.org/docs/latest/api/modules.html#modules_caching:

Caching

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.

like image 178
Michelle Tilley Avatar answered Sep 25 '22 00:09

Michelle Tilley