connect is not a function when connecting to mongodb

Error occurs when trying to run the function from the mongodb website that connects code to db.

const MongoClient = require('mongodb')

const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
  const collection = client.db("test").collection("devices");
  // perform actions on the collection object
  client.close();
});

Error is:

client.connect(err => {
  ^

    TypeError: client.connect is not a function

I have mongodb installed via npm and uri defined as the string they gave. Do I need anything else?

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

The reason is that you should import the MongoClient class:

const MongoClient = require("mongodb").MongoClient;

Instead of the following line in your code: const MongoClient = require("mongodb");

Solution 2

Try connecting this way:

const { MongoClient } = require("mongodb");

const uri = "yourUri...";
const databaseName = "yourDBName";

MongoClient.connect(uri, { useNewUrlParser: true }, (error, client) => {
  if (error) {
    return console.log("Connection failed for some reason");
  }
  console.log("Connection established - All well");
  const db = client.db(databaseName);
});

Solution 3

If you are using older version of MongoClient then try to install mongo client 2.2.33.

npm uninstall mongodb
npm install [email protected]

If you are using the newer version (3.0 and above) of mongo client then modify the code as shown below.

let MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017', function(err, client){
  if(err) throw err;
  let db = client.db('test');
  db.collection('devices').find().toArray(function(err, result){
    if(err) throw err;
    console.log(result);
    client.close();
    });
 });

Solution 4

const mongodb = require('mongodb').MongoClient();

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply