Search code examples
javascriptmongodbconnection

Connecting to MongoDB database


I am trying to connect to a MongoDB database.I have followed all the steps here https://youtu.be/EcJERV3IiLM but am getting an error.

The index.js file looks like this,

const dotenv = require('dotenv')
dotenv.config()
const mongodb = require('mongodb')

mongodb.connect(process.env.CONNECTIONSTRING, async function(err,client){
  const db = client.db()
  const results = await  db.collection("student").find().toArray()
  console.log(results)

The error I get is,

mongodb.connect is not a function

So it seems to be reading as far line 5:9 which is mongodb.connect in index.js and just stops.

I put this file index.js beside the .env file and beside that .gitignore which contains the the .env file. The .env file has the code which I copied from the Mongodb AtlSAS Cloud Service.

I also created a user and and autogenerated and saved a password. Both of which I placed in the string. And I put in the string the name of the database name "blah" The table/document is called "student". That's in the index.js code above. So the database name and the document name are blah.student.

I documented what I tried here, http://www.shanegibney.com/shanegibney/mongodb-setup/

The tutorial video is here, https://youtu.be/EcJERV3IiLM

I am on Ubuntu Linux.

I am currently running index.js in the terminal in a directory called mongostack, with

node index.js

but should I use,

nodemon index.js 

And for this should I install nodemon and how do I do that?

Do I need to download it first and if so where do I get it?


Solution

  • I think you need to get MongoClient. Try changing:

    const mongodb = require('mongodb')
    

    to:

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