2

I'm setting up a new app using an Atlas Database with node and all i get is an error saying " MongoError: MongoClient must be connected before calling MongoClient.prototype.db".

const uri = "mongodb+srv://alberto:pass@lel-kicis.mongodb.net/test";
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
  const collection = client.db("test").collection("students")
   .then(db => console.log('DB conectada'))
   .catch(err => console.log(error));
 });
Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
  • You did not check `err`. There was probably an error thrown which are ignoring, and most likely due to an authentication problem or unreachable host. Also `MongoClient.connect()` is the preferred and recommended method. It returns a `Promise`, so you can do `Mongoclient.connect(uriString).then(..code..).catch(err => console.error(err));` Or even use `async/await` unless your NodeJS is older than version 8. – Neil Lunn Mar 30 '19 at 07:10
  • Specifically see [this answer](https://stackoverflow.com/a/47662979/2313887) for a valid usage example. Except for the `client.close()`, which is something your application should probably **never** call. We only typically show that for short "example" listings. – Neil Lunn Mar 30 '19 at 07:14

3 Answers3

0

If you look at the mongodb connector docs, the syntax for MongoClient is new MongoClient(url, options, callback). The signature for the callback is (err, client) => { //body }.

If you don't pass in the optional callback, you get and instance of MongoClient (which is the case here). The connect method also expects the same callback signature, so your connection should be like:

const instance = new MongoClient(uri, { useNewUrlParser: true });
// notice 'client' in the callback
instance.connect((err, client) => {
  if (err) console.log('failed to connect')
  else {
    console.log('connected')
    const collection = client.db("test").collection("students")
    ...
  }
 });

mongodb connector also support promise, so you can also do:

// connection is a promise
const connection = instance.connect()
connection.then((err, client) => { // etc })
1565986223
  • 6,420
  • 2
  • 20
  • 33
0

Using mongoose and mongodb-uri :

Here is the way I initialise the connection :

const mongoose = require('mongoose')
const uriUtil = require('mongodb-uri')

// Create a new connection
mongoose.Promise = global.Promise
// mongoose.set('debug', DEBUG)

const dbURI = uriUtil.formatMongoose(process.env.MONGO_URI)

const options = {
    autoIndex: DEBUG,
    autoReconnect: true,
    useNewUrlParser: true
}  

const conn = mongoose.createConnection(dbURI, options)

conn.on('open', () => console.log('DB connection open'))
conn.on('error', err => console.log(`DB connection error : ${err.message}`, err))
conn.on('close', () => console.log('DB connection closed'))

module.exports = conn

Using the connection string provided by mongoDb for driver node.js version 3.0 or later.

Nicolas Oste
  • 142
  • 2
  • 8
-2

You are missing to initiate the mongo client.

const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://alberto:pass@lel-kicis.mongodb.net/test";
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
  const collection = client.db("test").collection("students")
   .then(db => console.log('DB conectada'))
   .catch(err => console.log(error));
 });

Also, Atlas generate the initial connection code block for you. Follow the below steps.

Clck on connect button

enter image description here

Select Connect Your Application from the next window

enter image description here

On the next window, Select NodeJs as driver and select the required version. Also, select Full driver example for full code block

enter image description here

Now copy the code and use it directly.

Mani
  • 1,471
  • 1
  • 13
  • 19