我只是将一个init函数分离到一个单独的文件中。它只在这里为管理员用户检查数据库,但将来我可以注册通过app
和db
对象的模块,我将使用async.each
异步加载模块,并在每个模块上运行init
方法以启动系统。一旦它们都在快速服务器上注册运行init
。
server.js:
'use strict';
// Set the 'NODE_ENV' variable
process.env.NODE_ENV = process.env.NODE_ENV || 'development';
process.env.PORT = process.env.PORT || 3000;
// Apparently __dirname doesn't work on Heroku
// @link http://stackoverflow.com/questions/17212624/deploy-nodejs-on-heroku-fails-serving-static-files-located-in-subfolders
process.env.PWD = process.cwd();
// Load the module dependencies
var mongoose = require('./server/config/mongoose'),
express = require('./server/config/express'),
init = require('./server/config/init');
// Create a new Mongoose connection instance
var db = mongoose();
// Create a new Express application instance
var app = express(db);
// Run the init this way in future refactor modules into separate folders.
init(app, db)
.then(function initialized() {
// Use the Express application instance to listen to the '3000' port
app.listen(process.env.PORT);
// Log the server status to the console
console.log('Server running at http://localhost:' + process.env.PORT + '/');
});
// Use the module.exports property to expose our Express application instance for external ussage
module.exports = app;
服务器/配置/ init.js:
'use strict';
var config = require('./config');
module.exports = function(app, db) {
return new Promise(function(resolve) {
var User = db.model('User');
User.findOne({ email: config.adminAccountEmail}, function(err, user) {
if (err) throw err;
if (!user) {
var newAdmin = new User({
email: config.adminAccountEmail,
password: config.adminAccountPassword,
roles: ['administrator', 'authenticated', 'anonymous']
});
newAdmin.save(function(err) {
if (err) throw err;
resolve();
})
} else {
resolve();
}
})
})
};
服务器/配置/ production.js:
'use strict';
/**
* Set the 'production' environment configuration object
* @link http://docs.mongolab.com/migrating/
*/
module.exports = {
db: process.env.MONGODB_URI,
// set this to build
// dir: 'build/',
dir: 'client/',
fileDir: 'files/',
sessionSecret: process.env.SESSION_SECRET || 'MEAN',
adminAccountEmail: process.env.ADMIN_ACCOUNT_EMAIL || '[email protected]',
adminAccountPassword: process.env.ADMIN_ACCOUNT_PASSWORD || 'password'
}
你为什么不只是在设置/启动快递之前检查您的superadmin用户是否存在? – Wake
因为它需要使用猫鼬进行异步调用。我应该使用waitfor节点模块在Express启动时同步运行该代码吗? –