Folgen Sie dem Beispiel aus meinem Kommentar, ändern Sie es, so dass die App Fehler behandelt, anstatt den Server nicht zu starten.
var express = require('express');
var mongodb = require('mongodb');
var app = express();
var MongoClient = require('mongodb').MongoClient;
var db;
// Initialize connection once
MongoClient.connect("mongodb://localhost:27017/integration_test", function(err, database) {
if(err) return console.error(err);
db = database;
// the Mongo driver recommends starting the server here because most apps *should* fail to start if they have no DB. If yours is the exception, move the server startup elsewhere.
});
// Reuse database object in request handlers
app.get("/", function(req, res, next) {
db.collection("replicaset_mongo_client_collection").find({}, function(err, docs) {
if(err) return next(err);
docs.each(function(err, doc) {
if(doc) {
console.log(doc);
}
else {
res.end();
}
});
});
});
app.use(function(err, req, res){
// handle error here. For example, logging and returning a friendly error page
});
// Starting the app here will work, but some users will get errors if the db connection process is slow.
app.listen(3000);
console.log("Listening on port 3000");
Ich weiß nicht, dass Sie wirklich wirklich eine neue Verbindung jedes Mal öffnen. Schauen Sie sich https://mongodb.github.io/node-mongodb-native/driver-articles/mongoclient.html#mongoclient-connection-pooling – Paul
an, aber in diesem Fall, wenn die Verbindung zur db nicht hergestellt werden konnte, wird der Server es selbst tun nicht auf sein. –
Das Grundmuster funktioniert immer noch. Ich werde eine Antwort auf diesen Effekt folgen. – Paul