Home > Net >  Connecrint to Mongodb
Connecrint to Mongodb

Time:04-19

I just can't connect to a mongodb. Here's what I tried

in node.js

console.log("001");
 dotenv = require('dotenv');
dotenv.config();
const mongodb = require('mongodb').MongoClient;

const { MongoClient } = require("mongodb");
console.log("002");
const uri = process.env.CONNECTIONSTRING;

const client = new MongoClient(uri);
console.log("003");
async function run() {
  console.log("004");
  client.connect();
  const db = client.db("blah");
  console.log("005");
  await const results = db.student.find();
  console.log("006")
  console.log(results)
  console.log("007")
  client.close()
};
//call function
run();

and I get this error

SyntaxError: Unexpected token 'const'

the CONNECTIONSTRING is in .env beside the original file node.js

The database is called 'blah' and the collection 'student'.

The error is on line 18,

 await const results = db.student.find();

Thanks,

CodePudding user response:

This isn't an answer.

But what I've tried is,

console.log("001");
 dotenv = require('dotenv');
dotenv.config();
const mongodb = require('mongodb').MongoClient;

const { MongoClient } = require("mongodb");
console.log("002");
const uri = process.env.CONNECTIONSTRING;

const client = new MongoClient(uri);
console.log("003");
async function run() {
  console.log("004");
  client.connect();
  const db = client.db("blah");
  console.log("005");
  const results = await db.student.find();
  console.log("006")
  console.log(results)
  console.log("007")
  client.close()
};
//call function
run();

The error I get is,

UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'find' of undefined

Thanks,

CodePudding user response:

Again this not an answer.

I changed the try{} catch{} blocks.

console.log("001");
 dotenv = require('dotenv');
dotenv.config();
const mongodb = require('mongodb').MongoClient;

const { MongoClient } = require("mongodb");
console.log("002");
const uri = process.env.CONNECTIONSTRING;

const client = new MongoClient(uri);
console.log("003");
async function run() {
  try{
  console.log("004");
  client.connect();
  const db = client.db("blah");
  console.log("005");

  const results = await  db.collection("student").find()

  console.log("006")

  console.log(results)
  console.log("007")
  client.close()
    console.log("hello");
  }
  catch{
console.log("try");
  }
  };


//call function
run();
  • Related