MongoError: MongoClient must be connected before calling

I have a web resource

when localhost then good

but when online show a DB error

MongoError: MongoClient must be connected before calling MongoClient.prototype.db
    at MongoClient.db (/home/pgewvedi/yp/node_modules/mongodb/lib/mongo_client.js:314:11)
    at Object.exports.model (/home/pgewvedi/yp/views/Content/Model/index.js:167:38)
    at Function.$.getModel (/home/pgewvedi/yp/app.js:121:101)
    at Object.index (/home/pgewvedi/yp/views/Home/Controller/index.js:3:11)
    at Function.$.setController (/home/pgewvedi/yp/app.js:110:73)
    at /home/pgewvedi/yp/views/Home/Config.js:3:11
    at Layer.handle [as handle_request] (/home/pgewvedi/yp/node_modules/express/lib/router/layer.js:95:5)
    at next (/home/pgewvedi/yp/node_modules/express/lib/router/route.js:131:13)
    at Route.dispatch (/home/pgewvedi/yp/node_modules/express/lib/router/route.js:112:3)
    at Layer.handle [as handle_request] (/home/pgewvedi/yp/node_modules/express/lib/router/layer.js:95:5)

can you provide a simple web resource connected to DB success?

Hello :wave: @Lam_Cao_I_nh,

Could you please try the following code to establish a connection to your MongoDB database?

import { MongoClient } from 'mongodb';

const uri = 'uri'; // Replace 'uri' with your actual MongoDB connection string
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });

client.connect(err => {
    if (err) {
        console.error('Error connecting to MongoDB:', err);

    console.log('Connected to MongoDB server...');

    const db = client.db('testdb'); // Replace 'testdb' with your database name
    const collection = db.collection('coll'); // Replace 'coll' with your collection name

    collection.find({}).toArray((err, result) => {
        if (err) {
            console.error('Error executing find query:', err);

        console.log('Find query executed...');

        client.close(); // Close the MongoDB connection

The provided code is an example of connecting to a MongoDB database and performing a basic query. Please make sure to adapt the code by replacing the placeholders with your actual MongoDB connection string, database name, and collection name.

If the issue persists, it would be helpful to provide additional context by sharing the following details:

  1. What type of MongoDB Deployment are you using, such as on-prem or MongoDB Atlas?
  2. Are you utilizing any specific frameworks or libraries?
  3. What are the version of Node.js you are currently using and the code you are executing?
  4. What is the version of MongoDB that your localhost is running with which your connection was successful?

Best regards,

thank you ^^ :+1: :+1:

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.