node.js - 将模型存储在文件夹中,使用 index.js 全部要求

标签 node.js commonjs

我有一个规模不错的项目,我需要进行一些重组。

我正在使用 mongoose 作为我的 Node ORM。我想把我所有的 Mongoose 模型放在一个名为“模型”的文件夹中。我已经读过,当我这样做时,我可以在模型文件夹中放置一个 index.js 文件,这样就可以拉入所有模型并存储它们。

app.js:

...
var mongoose = require('mongoose');
var models = require('./models')(mongoose);

app.configure(function () {
  mongoose.connect(dbPath, function(err) {
    if (err) throw err;
  });
  ...
});

// include models in my routes so I need access
...

我被困在 index.js 中返回我的所有模型需要做什么

index.js(这是我尝试过的,甚至没有关闭)

function Models(mongoose) {
    var Counters = require('./counters')(mongoose);
    var User = require('./user')(mongoose);
    var Token = require('./token')(mongoose);
    var Team = require('./team')(mongoose);
    var Role =  require('./role')();
    var Layer = require('./layer')(mongoose, counters);
    var Feature = require('./feature')(mongoose, counters, async);


}

module.exports = Models;

我还应该从 app.js 传入 mongoose,因为我需要在那里连接到 mongo? IE。我可以在 index.js 中再次要求它,但我不确定在不同的文件中要求相同的模块是否是不好的做法。

编辑:(这是我的模型)

抱歉,我在模型类中添加了“访问器”类型的函数。 IE。我想为每个模型提供一个公共(public)接口(interface)。

user.js:

module.exports = function(mongoose) {

  // Creates a new Mongoose Schema object
  var Schema = mongoose.Schema; 

  // Collection to hold users
  var UserSchema = new Schema({
      username: { type: String, required: true },
      password: { type: String, required: true },
    },{ 
      versionKey: false 
    }
  );

  // Creates the Model for the User Schema
  var User = mongoose.model('User', UserSchema);

  var getUserById = function(id, callback) {
    User.findById(id, callback);
  }

  var getUserByUsername = function(username, callback) {
    var query = {username: username};
    User.findOne(query, callback);
  }


  return {
    getUserById: getUserById,
    getUserByUsername: getUserByUsername
  }
} 

最佳答案

在 node.js 中,模块在第一次加载后被缓存。所以你不需要从 app.js 传递 mongoose

例如在models/index.js中:

require('./counters')
exports.User = require('./user')
require('./token');
require('./team');
require('./role');
require('./layer');
require('./feature');
// I prefer to use a loop to require all the js files in the folder.

在模型/user.js 中:

var mongoose = require('mongoose');
var userSchema = mongoose.Schema({
  // ... Define your schema here
});

var User = module.exports = mongoose.model('User', userSchema);
module.exports.getUserById = function(id, callback) {
  User.findById(id, callback);
}

module.exports.getUserByUsername = function(username, callback) {
  var query = {username: username};
  User.findOne(query, callback);
}

在 app.js 中:

var mongoose = require('mongoose');
var models = require('./models');

mongoose.connect(dbPath, function(err) {
  if (err) throw err;
});

// Yes! You can use the model defined in the models/user.js directly
var UserModel = mongoose.model('User');

// Or, you can use it this way:
UserModel = models.User;

app.get('/', function(req, res) {
  var user = new UserModel();
  user.name = 'bob';
  user.save();
  // UserModel.getUserByUsername();
  ...
});

详细了解 node.js 中的模块缓存: http://nodejs.org/api/modules.html#modules_caching

关于node.js - 将模型存储在文件夹中,使用 index.js 全部要求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17246981/

相关文章:

node.js - WebPack 和 Express 服务器无法协同工作

javascript - 需要外部 JavaScript 文件

javascript - 无法从 Node.js 中的 typescript 文件中要求默认导出的函数

node.js - 为什么我电脑中的node.js版本比当前官方版本高?

node.js - NodeJS : Unhandled Promise Rejection at the end of a method

javascript - sinon:如何 stub 实例方法

javascript - 为什么只说 CommonJS 适用于非浏览器应用?

javascript - 将变量注入(inject) webpack

javascript - 未找到命名导出 'Types'。请求的模块 'mongoose' 是一个 CommonJS 模块,它可能不支持所有 module.exports 作为命名导出

node.js - firehose 上的模拟 putRecord 无法与 aws-sdk-mock 一起使用