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

tut*_*ley 5 mongoose mongodb node.js express pug

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

如何在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);
Run Code Online (Sandbox Code Playgroud)

到目前为止,我为"siteConfig"集合创建了一个名为"Site"的模型,我在accessDB.js中有一个名为getSiteConfig的函数,它运行Site.find()...以检索集合中一个文档中的字段.

所以这就是问题的症结所在:我应该如何将这些字段注入Express应用程序,以便它们可以在整个站点中使用?我应该使用与moment.js工具相同的模式吗?像这样:

db.getSiteConfig(function(err, siteConfig){
  if (err) {throw err;}
  app.locals.siteConfig = siteConfig;
});
Run Code Online (Sandbox Code Playgroud)

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

谢谢!

Leo*_*tny 20

考虑使用快速中间件来加载站点配置.

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();
    });
  });
  ...
});
Run Code Online (Sandbox Code Playgroud)

投掷错误是一个非常糟糕的主意,因为它会使您的应用程序崩溃.所以请next(err);改用.它会传递你的错误来表达errorHandler.

如果您已经对用户进行了身份验证(例如,在之前的中间件中)并将其数据存储到其中req.user,则可以使用它从db获取正确的配置.

但是要小心getSiteConfig在快速中间件中使用你的功能,因为它会暂停进一步处理请求,直到收到数据.

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

以下代码演示了siteConfig在express session 中缓存的想法:

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();
    });
  });
  ...
});
Run Code Online (Sandbox Code Playgroud)