Mongoose和NodeJS项目的文件结构

Don*_*ker 59 mongoose node.js

我目前在/models/models.js文件中为我的Mongoose/NodeJS应用程序提供了所有模型(模式定义).

我想将这些分成不同的文件:user_account.js,profile.js等.但是我似乎无法这样做,因为我的控制器断开并报告" 无法找到模块 "一旦我将这些类拆开.

我的项目结构如下:

/MyProject
  /controllers
    user.js
    foo.js
    bar.js
    // ... etc, etc
  /models
    models.js
  server.js
Run Code Online (Sandbox Code Playgroud)

我的models.js文件的内容如下所示:

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

mongoose.connect('mongodb://localhost/mydb');

var UserAccount = new Schema({
    user_name       : { type: String, required: true, lowercase: true, trim: true, index: { unique: true } }, 
    password        : { type: String, required: true },
    date_created    : { type: Date, required: true, default: Date.now }
}); 

var Product = new Schema({
    upc             : { type: String, required: true, index: { unique: true } },
    description     : { type: String, trim: true },
    size_weight     : { type: String, trim: true }
});
Run Code Online (Sandbox Code Playgroud)

我的user.js文件(控制器)看起来像这样:

var mongoose    = require('mongoose'), 
    UserAccount = mongoose.model('user_account', UserAccount);

exports.create = function(req, res, next) {

    var username = req.body.username; 
    var password = req.body.password;

    // Do epic sh...what?! :)
}
Run Code Online (Sandbox Code Playgroud)

如何将模式定义分解为多个文件并从控制器中引用它?当我引用它时(在架构在新文件之后)我收到此错误:

*错误:尚未为模型"user_account"注册架构.*

思考?

Pet*_*ons 95

这是一个样本 app/models/item.js

var mongoose = require("mongoose");

var ItemSchema = new mongoose.Schema({
  name: {
    type: String,
    index: true
  },
  equipped: Boolean,
  owner_id: {
    type: mongoose.Schema.Types.ObjectId,
    index: true
  },
  room_id: {
    type: mongoose.Schema.Types.ObjectId,
    index: true
  }
});

var Item = mongoose.model('Item', ItemSchema);

module.exports = {
  Item: Item
}
Run Code Online (Sandbox Code Playgroud)

要从项目控制器加载它,app/controllers/items.js我会这样做

  var Item = require("../models/item").Item;
  //Now you can do Item.find, Item.update, etc
Run Code Online (Sandbox Code Playgroud)

换句话说,在模型模块中定义模式和模型,然后只导出模型.使用相对要求路径将模型模块加载到控制器模块中.

要建立连接,请在服务器启动代码(server.js或其他)中尽早处理.通常,您需要从配置文件或环境变量中读取连接参数,如果未提供配置,则默认为开发模式localhost.

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost');
Run Code Online (Sandbox Code Playgroud)

  • 我更新了我的答案以解决这一问题. (4认同)

小智 35

这里的几个答案真的帮助我开发了另一种方法.原来的问题是关于打破只是模式定义出来,但我更愿意捆绑在同一个文件的架构和模型定义.

这主要是Peter的想法,只是通过重写module.exports来导出模型定义,以便从控制器访问模型一点点冗长:

项目布局:

MyProject
  /controllers
    user.js
    foo.js
    bar.js
    // ... etc, etc
  /models
    Item.js
  server.js
Run Code Online (Sandbox Code Playgroud)

models/Item.js看起来像:

var mongoose = require("mongoose");

var ItemSchema = new mongoose.Schema({
  name: {
    type: String,
    index: true
  }
});

module.exports = mongoose.model('Item', ItemSchema); 
// Now `require('Item.js')` will return a mongoose Model,
// without needing to do require('Item.js').Item
Run Code Online (Sandbox Code Playgroud)

您可以在控制器中访问模型,例如user.js,例如:

var Item = require(__dirname+'/../models/Item')

...

var item = new Item({name:'Foobar'});
Run Code Online (Sandbox Code Playgroud)

不要忘记在server.js中调用mongoose.connect(..),或者你认为合适的地方!


小智 12

我最近回答了有关同一问题的Quora问题. http://qr.ae/RoCld1

我发现非常好并节省了需要 调用的数量是将模型构建到一个目录中.确保每个文件只有一个模型.

在与模型相同的目录中创建index.js文件.将此代码添加到其中.一定要添加必要的fs要求

var fs = require('fs');

/*
 * initializes all models and sources them as .model-name
 */
fs.readdirSync(__dirname).forEach(function(file) {
  if (file !== 'index.js') {
    var moduleName = file.split('.')[0];
    exports[moduleName] = require('./' + moduleName);
  }
});
Run Code Online (Sandbox Code Playgroud)

现在您可以按如下方式调用所有模型:

var models = require('./path/to/models');
var User = models.user;
var OtherModel = models['other-model'];
Run Code Online (Sandbox Code Playgroud)

  • 这是迄今为止最好的答案,自动化在代码中节省了大量冗余,并且最终看起来非常干净。 (2认同)
  • 我假设您的数据库初始化代码位于项目根目录中。知道它的表现如何吗?谢谢 (2认同)

use*_*015 8

Peter Lyons几乎涵盖了基础.
借用上面的例子(删除模式后的行)我只想添加:

app/models/item.js

note: notice where `module.exports` is placed
var mongoose = require("mongoose");

var ItemSchema = module.exports = new mongoose.Schema({
  name: {
    type: String,
    index: true
  },
  ...

});
Run Code Online (Sandbox Code Playgroud)

从中加载它 app/controllers/items.js

var mongoose = require('mongoose');
var Item = mongoose.model('Item', require('../models/item'));  
Run Code Online (Sandbox Code Playgroud)

没有module.exports或的另一种方式require:

app/models/item.js

var mongoose = require("mongoose");

var ItemSchema = new mongoose.Schema({
  name: {
    type: String,
    index: true
  },
  ... 

});

mongoose.model('Item', ItemSchema); // register model
Run Code Online (Sandbox Code Playgroud)

在里面 app/controllers/items.js

var mongoose = require('mongoose')
  , Item = mongoose.model('Item');  // registered model
Run Code Online (Sandbox Code Playgroud)