我正在使用DailyJS上的Nodepad教程。我已经分叉了它,并正在扩展它以用于我自己的目的。我遇到的一个问题是整个应用程序都写在文件中,我更喜欢将我的应用程序分开一点。我应该如何将 mongo 写入我的单独模型文件,因为与 mongoose 相关的所有内容都在.app.js
app.js
我需要将什么带入我的外部文件,以便它们能够正确连接到数据库并理解我的猫鼬模式?
最简单的方法是在应用程序初始化时向 Mongoose 注册模型,然后当您想要使用它们时,只需从 Mongoose 检索它们,而不是再次要求“用户”。
您还可以通过打开 Mongoose 的默认连接来使事情变得更容易,除非您有特定要求,这意味着您必须手动管理每个连接。
像这样做:
应用程序.js
var mongoose = require('mongoose');
require('./models/user');
mongoose.connect('server', 'database');
模型/user.js
var mongoose = require('mongoose')
, Schema = mongoose.Schema
, ObjectId = Schema.ObjectId;
UserSchema = new Schema({
email: {type: String, "default": ''},
created_at: {type: Date, Date.now}
});
mongoose.model('User', UserSchema); // no need to export the model
其他任何地方...
var mongoose = require('mongoose')
, User = mongoose.model('User');
var u = new User({email: 'youremail@something.com'});
u.save();
这是一个直接从Gitpilot中提取的示例:
用户.js:
var mongoose = require('mongoose')
, Schema = mongoose.Schema
, ObjectId = Schema.ObjectId; //not needed here, but may be needed in another model file
UserSchema = new Schema({
email: {type: String, "default": ''},
created_at: {type: Date, Date.now}
});
User = mongoose.model('users', UserSchema); //name of collection is 'users'
module.exports.User = User;
module.exports.Schema = UserSchema;
然后在你的另一个文件中......
var mongoose = require('mongoose')
, User = require('./user').User;
mongoose.connection.once('open', function() {
var u = new User({email: 'youremail@something.com'});
u.save();
});
mongoose.connect(); //default connect to localhost, 27017
User
注意:为简洁起见,从模型中删除了一些字段。希望这可以帮助。