0

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 wrong with the asynchronous running.

const client = new MongoClient(apiconfig.mongoUrl, {
    useNewUrlParser: true
});

app.get("/api/:object", (req, res) => {
    mongodb(req.params["object"], async (collection: Collection) => {
        if (collection !== undefined) {
            let result = await collection.find().toArray();
            res.send(result);
        }
        else {
            res.sendStatus(404);
        }
    });
});

const mongodb = (coll: string, operation: (collection: Collection) => Promise<void>) => {
    client.connect((err) => {
        const db = client.db("VaorraJS");
        db.collections().then((collections) => {
            operation(collections.find((collection) => collection.collectionName === coll)).then(() => {
                client.close();
            });
        }).catch((error) => {
            console.log("ERROR: " + error);
        });
    });
}

app.listen(5000);
Koflin
  • 67
  • 1
  • 7

1 Answers1

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);
});
Rahul Sharma
  • 9,534
  • 1
  • 15
  • 37
  • But isn't the connection going to timeout after a big amount of time? – Koflin Apr 05 '19 at 15:00
  • @Koflin can you share what's error are you getting? – Rahul Sharma Apr 06 '19 at 06:18
  • You fixed my error thanks, but I am still concerned that the connection will timeout after a big amount of time. Do you think it will? – Koflin Apr 06 '19 at 12:13
  • I don't think so, Timeout happens if the server is not able to connect to the database. In this, I don't see any problem until and unless mongo server is down. – Rahul Sharma Apr 06 '19 at 12:44
  • How to solve same problem in scenario of Serverless function. The serverless calls are instances in itself so they will create a connection right? I am having similar problem posted [here](https://stackoverflow.com/questions/65903333/mongoerror-topology-was-destroyed-while-using-with-nextjs-api). – Rupam Kairi Jan 26 '21 at 15:06