Home > Back-end >  connecting to mongodb database
connecting to mongodb database

Time:04-17

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?

I just can''t think of anything else to do.

Any help would be greatly appreciated.

Thanks,

CodePudding user response:

I think you need to get MongoClient. Try changing:

const mongodb = require('mongodb')

to:

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

CodePudding user response:

You have to create a MongoClient see https://www.mongodb.com/docs/drivers/node/current/quick-start/

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

const uri = process.env.CONNECTIONSTRING;
const client = new MongoClient(uri);
async function run() {
  await client.connect();
  const db = client.db("yourdb")
  const results = await db.collection("student").find().toArray()
  console.log(results)
}
run();
  • Related