Every Second Run Throws: Mongoerror: Topology Was Destroyed
I am building a REST API but every second time I load my site I get a MongoError: Topology was destroyed. Can someone help me fixing this? I have a feeling that there is something
Solution 1:
I would suggest the use Mongoose
you are creating DB connection for every request, which is not the correct way
const MongoClient = require('mongodb').MongoClient;
// Connection URL
const url = 'mongodb://localhost:27017';
// Database Name
const dbName = '<some db>';
// Use connect method to connect to the server
let db;
MongoClient.connect(url, function (err, client) {
assert.equal(null, err);
console.log("Connected successfully to server");
db = client.db(dbName);
});
app.get("/api/:object", async(req, res) => {
const collection = db.collection(req.params["object"]);
let result = await collection.find().toArray();
res.send(result);
});
Post a Comment for "Every Second Run Throws: Mongoerror: Topology Was Destroyed"