如何在MongoDB中为NodeJS Express应用程序存储站点configuration?

我有一个使用MongoDB和Jade模板语言在NodeJS 0.8.8上运行的Expressjs应用程序,我希望允许用户configuration许多站点范围的显示选项,例如页面标题,徽标图像等。

我如何将这些configuration选项存储在mongoDB数据库中,以便我可以在应用程序启动时读取它们,在应用程序运行时操作它们,并将它们显示在jade模板中?

这是我的一般应用程序设置:

var app = module.exports = express(); global.app = app; var DB = require('./accessDB'); var conn = 'mongodb://localhost/dbname'; var db; // App Config app.configure(function(){ ... }); db = new DB.startup(conn); //env specific config app.configure('development', function(){ app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); }); // etc // use date manipulation tool moment app.locals.moment = moment; // Load the router require('./routes')(app); 

到目前为止,我已经为“siteConfig”集合创build了一个名为“Site”的模型,并且在accessDB.js中有一个名为getSiteConfig的函数,它运行Site.find()…以检索集合中的一个文档中的字段。

所以这就是问题的症结所在:我应该如何将这些字段注入快速应用程序,以便在整个网站中使用? 我是否应该遵循与moment.js工具相同的模式? 喜欢这个:

 db.getSiteConfig(function(err, siteConfig){ if (err) {throw err;} app.locals.siteConfig = siteConfig; }); 

如果没有,那么这样做的正确方法是什么?

谢谢!

考虑使用快递中间件来加载站点configuration。

 app.configure(function() { app.use(function(req, res, next) { // feel free to use req to store any user-specific data return db.getSiteConfig(req.user, function(err, siteConfig) { if (err) return next(err); res.local('siteConfig', siteConfig); return next(); }); }); ... }); 

抛出一个错误是一个真正的坏主意,因为它会导致应用程序崩溃。 所以使用next(err); 代替。 它会通过你的错误来expressionerrorHandler

如果您已经validation了您的用户(例如,在以前的中间件中)并将其数据存储到req.user ,则可以使用它从db中获取正确的configuration。

但是在Express中间件里面使用getSiteConfig函数要小心,因为它会暂停表示,直到接收到数据为止。

您应该考虑在快速会话中cachingsiteConfig以加速您的应用程序。 在会话中存储特定于会话的数据是绝对安全的,因为用户无法访问它。

以下代码演示了在快速sessionn中cachingsiteConfig的想法:

 app.configure(function() { app.use(express.session({ secret: "your sercret" })); app.use(/* Some middleware that handles authentication */); app.use(function(req, res, next) { if (req.session.siteConfig) { res.local('siteConfig', req.session.siteConfig); return next(); } return db.getSiteConfig(req.user, function(err, siteConfig) { if (err) return next(err); req.session.siteConfig = siteConfig; res.local('siteConfig', siteConfig); return next(); }); }); ... });