【发布时间】:2012-03-03 02:36:01
【问题描述】:
目前,我的 Mongoose/NodeJS 应用程序的 /models/models.js 文件中包含我的所有模型(架构定义)。
我想将它们分成不同的文件,例如:user_account.js、profile.js 等。但是我似乎无法这样做,因为我的控制器中断并报告“找不到模块强>”一旦我把这些类分开。
我的项目结构如下:
/MyProject
/controllers
user.js
foo.js
bar.js
// ... etc, etc
/models
models.js
server.js
我的 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 }
});
我的 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?! :)
}
如何将架构定义分解为多个文件并从我的控制器中引用它?当我确实引用它时(在架构位于新文件中之后)我收到此错误:
*错误:尚未为模型“user_account”注册架构。*
想法?
【问题讨论】:
-
我写了 mongoose-glue 模块来帮助构建你的 mongoose 模型:github.com/xpepermint/mongoose-glue