0

I am new to MongoDB. I am trying to establish a connection between my ExpressJS server and a MongoDB database. This is my code:

const PRIMARY_SERVER = "mongodb://localhost:27017/";

const { MongoClient } = require("mongodb");
const client = new MongoClient(PRIMARY_SERVER, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

async function connect() {
  try {
    await client.connect();
    console.log("Connected");
    module.exports = client.db("mydb");
    const app = require("../app.js");
    app.listen(5050);
  } catch (e) {
    console.error(e);
  } finally {
    await client.close();
  }
}
connect();

The connection gets established fine but as soon as this function gets called:

router.post("/pushbill", async function (req, res) {
    databaseConnection.collection("bills").insertOne(object, function(err, result){
        if(err) {
            result.status(400).send("Error inserting matches.");
        } else {
            console.log(`Added a new match with id 0`);
            result.status(204).send();
        }
  });
});

I get this error: "(node:17984) UnhandledPromiseRejectionWarning: TypeError: databaseConnection.collection is not a function".

I've searched for this issue for a few hours now but can't seem to find a solution. I tried several different methods of connecting my database, one of them included this ticket: db.collection is not a function when using MongoClient v3.0 . I am using MongoDB 4.13.0.

1 Answers1

0

It was an issue where the connection to MongoDB kept closing before any operation was made. I solved this issue by opening connection each time a request gets made, and waiting till the operations are done with a callback or in this case a timeout.

const connDB = async(operations, response) => {
  try{
    const client = new MongoClient('mongodb ip here', {
      useNewUrlParser: true,
      useUnifiedTopology: true,
    });
    await client.connect().then(function(result){
    }).catch(function(err){
      throw err;
    });
    const db = await client.db('my_db');
    operations(db);
    setTimeout(() => {client.close()}, 1500)
  } catch(err){
    console.error(err);
    response.status(500).send({ message: 'Error connecting or operating the database', error: err});
    await client.close();
  }
}