Home > Enterprise >  Error while trying to connect my Express app with MongoDB Atlas
Error while trying to connect my Express app with MongoDB Atlas

Time:01-02

I've almost finished my app and I want to connect my MongoDB database to the serverless platform MongoDB Atlas. Until then, I've been using my database in localhost (with mongosh) and it worked perfectly fine. Now I've changed "mongodb://localhost" to the adress of my database and I get an error : MongoNotConnectedError: MongoClient must be connected to perform this operation

Here is my code in db-connection.js :

require('dotenv').config();
let { MongoClient } = require('mongodb');

function connect(collection) {
    let client = new MongoClient(`mongodb srv://${process.env.DB_USER}:${process.env.DB_PASSWORD}@calendrier-delle.2rqpi.mongodb.net/calendrierdelle?retryWrites=true&w=majority`);
    client.connect();
    let calendrierDelle = client.db('calendrierdelle');
    let collections = calendrierDelle.collection(`${collection}`);

    return collections;
}

module.exports = { connect };

And a snippet of my code in server.js :

require('dotenv').config();
let express = require("express");
let app = express();
let dbConnection = require("./db-connection.js");

//Here is an example of how I make an query
let query = dbConnection.connect("aCollection").find({
   something: (some value),
}).toArray();
query.then((data) => { /* Do something with the data */ });

To precise :

• I don't use mongoose because I don't really need, and I'm lazy to change lol.

• On MongoDB Atlas, I've added an IP adress 0.0.0.0/0

• My username and password are goods

• Here is a screenshot of my cluster's name and db's nameMongoDB Atlas

In my code to connect with my database, I don't really understand why at the end of the url I connect my app with the database, and after I have to do the same thing : client.db('calendrierdelle'). I think here is my problem but I don't know how to solve it : I've tried everything (changing url, omit my calendrierDelle variable etc...).

Can you help me please ? Thanks !

PS : sorry I've added a mongoose tag to that post, I don't use it, but it's pretty close to my problem.

CodePudding user response:

JavaScript is asynchronous, meaning actions don't wait for the action before it to finish. You tried to do stuff on the database without waiting for MongoDB to connect. Fortunately, MongoDB doesn't make it too hard with Promises, and async/await. You can make things "wait" for Mongo to connect like so:

require('dotenv').config();
let { MongoClient } = require('mongodb');

async function connect(collection) {
    let client = new MongoClient(`mongodb srv://${process.env.DB_USER}:${process.env.DB_PASSWORD}@calendrier-delle.2rqpi.mongodb.net/calendrierdelle?retryWrites=true&w=majority`);
    await client.connect();
    let calendrierDelle = client.db('calendrierdelle');
    let collections = calendrierDelle.collection(`${collection}`);

    return collections;
}

module.exports = { connect };

Notice the await in front of client.connect(). Also notice that the connect function has async in front of it. Until the lastest versions of NodeJS, await must be in an async function.

CodePudding user response:

require('dotenv').config();
let { MongoClient } = require('mongodb');

const url = 
`mongodb srv://${process.env.DB_USER}:${process.env.DB_USER_PASSWORD}@
${process.env.DB_CLUSTER}.mongodb.net`;

async function connectDatabase() => {
    const client = await MongoClient.connect(url, {
    useNewUrlParser: true,
    useUnifiedTopology: true
});
const db = client.db("main");

return {
    listings: db.collection("test_listings")
  };
};

module.exports = { connectDatabase };
  • Related