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.