Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 606
theloosygoose Avatar asked May 07 '19 15:05

theloosygoose


People also ask

Why is my MongoDB not connecting?

If you have created a user and are having trouble authenticating, try the following: Check that you are using the correct username and password for your database user, and that you are connecting to the correct database deployment. Check that you are specifying the correct authSource database in your connection string.

Which function is used to create connection in MongoDB?

The connect method is used to establish a connection to a MongoDB objects. The method returns the reference to the database also. We can use the Mongo () instance and its getDB() method instead in some cases.

How do I connect to a specific database in MongoDB?

Connect to a Single MongoDB Instance const MongoClient = require('mongodb'). MongoClient; const assert = require('assert'); // Connection URL const url = 'mongodb://localhost:27017'; // Database Name const dbName = 'myproject'; // Use connect method to connect to the server MongoClient.


1 Answers

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");

like image 93
Leon Gilyadov Avatar answered Sep 30 '22 10:09

Leon Gilyadov