0

Expressミドルウェアを順番に呼び出す方法がわかりません。前のミドルウェアが完了してから次のミドルウェアを実行したいと考えています。そのためには next() を呼び出さなければならないと思っていましたが、明らかにそうではありません。

mongoose.connect(app.set("db-uri"));

app.use(function(req, res, next) {
 if(1 !== mongoose.connection.readyState) {
    console.log('Database not connected');
    res.render("system/maintenance", {
      status: 500
    });
  } else {
    return next();
  }
});


// This middleware does not wait for the previous next(). It just tries to connect before actually.
app.use(express.session({
  secret: settings.sessionSecret,
  maxAge: new Date(Date.now() + 3600000),
  store: new MongoStore({ mongoose_connection: mongoose.connections[0], auto_reconnect: true })
}));

編集:開始時にMongooseのみを接続し、ミドルウェアで状態を確認するようにコードを更新しました

4

2 に答える 2

0

これはうまくいくようです。ここで問題に関するコメントを受け付けています。

var store;
mongoose.connect(app.set("db-uri"));
mongoose.connection.on("connect", function(err) {
  // Create session store connection
  store = new MongoStore({ mongoose_connection: mongoose.connections[0], auto_reconnect: true });
});


app.use(function(req, res, next) {
  if(1 !== mongoose.connection.readyState) {
    console.log('Database not connected');
    // Try a restart else it will stay down even when db comes back up
    mongoose.connect(app.set("db-uri"));
    res.render("system/maintenance", {
      status: 500
    });
  } else {
    return next();
  }
});

app.use(express.session({
  secret: settings.sessionSecret,
  maxAge: new Date(Date.now() + 3600000),
  store: store
}));

動作しているように見える - セッション ストアが元に戻らないのではないかと心配していましたが、動作すると思います。

于 2013-08-29T18:33:22.307 に答える