Tra*_*Liu 6 redundancy arguments require mongoose node.js
我有以下Node.js目录结构.
|--app/
|--app.js
|--routers/
|--index.js/
|--models/
|--schemas.js
|--post.js
Run Code Online (Sandbox Code Playgroud)
在app.js中,有一条线就像这样mongoose.connect('mongodb://localhost/' + config.DB_NAME);.在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;
Run Code Online (Sandbox Code Playgroud)
在post.js中:
var mongoose = require('mongoose')
, PostSchema = require('./schemas').PostSchema
, PostModel = mongoose.model('Post', PostSchema);
module.exports = PostModel;
Run Code Online (Sandbox Code Playgroud)
在index.js中,可能有一行喜欢这样:var PostModel = require('../models/post');.上面提到的所有文件都需要mongoose.schemas.js的目的是帮助程序员在单个文件中掌握数据库的模式.但是,我想知道这个工具是否会导致冗余并导致更多开销,因为我需要mongoose.我应该把它作为一个参数传递吗?
如果你只是担心性能,你不必是.根据http://nodejs.org/docs/latest/api/modules.html#modules_caching:
高速缓存
模块在第一次加载后进行缓存.这意味着(除其他外)每个调用
require('foo')将返回完全相同的对象,如果它将解析为同一个文件.多次调用
require('foo')可能不会导致模块代码多次执行.这是一个重要的特征.有了它,就可以返回"部分完成"的对象,从而允许加载传递依赖,即使它们会导致循环.如果要让模块多次执行代码,则导出一个函数,然后调用该函数.
所以,你requiring每次都不是猫鼬; 相反,每次在第一次之后,返回缓存的Mongoose模块.