TypeError: db.collection is not a function

node.jsMongodbRestExpress

node.js Problem Overview


I am trying to post data to database that I have created on mLab and I am getting this error but I don't know whats going wrong.I also have read previously asked question on this topic but I am not able to solve my error as I am new to this. So here I am posting the code which I am trying to implement and It is taken from this tutorial https://medium.freecodecamp.com/building-a-simple-node-js-api-in-under-30-minutes-a07ea9e390d2.

server.js

const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const bodyParser = require('body-parser');

const db = require('./config/db');


const app = express();

const port = 8000;

app.use(bodyParser.urlencoded({extened:true}));


MongoClient.connect(db.url,(err,database) =>{
	
	if (err) return console.log(err)
	require('./app/routes')(app,{});
	app.listen(port,() => {
		console.log("We are live on"+port);	
	});

})

db.js

module.exports = {
  url : "mongodb://JayTanna:[email protected]:47510/testing"
};

index.js

const noteroutes = require('./note_routes');

module.exports = function(app,db)
{
	noteroutes(app,db);
	
};

note_routes.js

module.exports = function(app, db) {
  app.post('/notes', (req, res) => {
    const note = { text: req.body.body, title: req.body.title };
    db.collection('notes').insert(note, (err, result) => {
      if (err) { 
        res.send({ 'error': 'An error has occurred' }); 
      } else {
        res.send(result.ops[0]);
      }
    });
  });
};

node.js Solutions


Solution 1 - node.js

So I voted for the answer which said to just go down to mongodb 2.2.33 because I tried it and it worked, but then I felt weird about just downgrading to fix a problem so I found the solution which allows you to keep version >= 3.0. If anyone finds this issue and their problem wasn't passing in a blank reference like the accepted answer, try this solution out.

When you run..

MongoClient.connect(db.url,(err,database) =>{ }

In mongodb version >= 3.0, That database variable is actually the parent object of the object you are trying to access with database.collection('whatever'). To access the correct object, you need to reference your database name, for me that was by doing

MongoClient.connect(db.url,(err,database) =>{ 
  const myAwesomeDB = database.db('myDatabaseNameAsAString')
  myAwesomeDB.collection('theCollectionIwantToAccess')
}

This fixed my errors when running my node.js server, hopefully this helps somebody who doesn't just want to downgrade their version.

(also, if you don't know your db name for some reason, just do a console.log(database) and you'll see it as an object attribute)


EDIT (June 2018):

According to this, the callback actually returns the connected client of the database, instead of the database itself.

Therefore, to get the database instance, we need to use this method, which takes in a dbName. In the documentation it said If not provided, use database name from connection string., as mentioned by @divillysausages in the comments below.

In short, we should call database.db().collection('theCollectionIwantToAccess'); if the dbName is provided by url, where the database is actually client for better understanding

Solution 2 - node.js

The error is in the mongodb library. Try to install version 2.2.33 of mongodb. Delete your node_modules directory and add

"dependencies": {
   "mongodb": "^2.2.33"
}

Then

npm install

and there you are

Solution 3 - node.js

MongoClient.connect(uristring, function (err, database) {
      var db=database.db('chatroomApp');
      var collections=db.collection('chats');
});

Need to Get the Database first before trying to access the collections.

Solution 4 - node.js

According to the mongo document, we need to change the connection as bellow,

The legacy operation
MongoClient.connect('mongodb://localhost:27017/test', (err, db) => {
    // Database returned
});

is replaced with
MongoClient.connect('mongodb://localhost:27017/test', (err, client) => {
    // Client returned
    var db = client.db('test');
});

Don't need to downgrade the mongo version :)

Solution 5 - node.js

Uninstalling existing mongodb package and reinstalling using the following commands resolved the issues for me. :)

npm uninstall mongodb --save

npm install mongodb@2.2.33 --save

PS: Thanks to @MihirBhende and @yaxartes

FYI,

Prefer non-rc releases from https://github.com/mongodb/node-mongodb-native/releases, if you are new to the field.

Solution 6 - node.js

In your server.js, you are passing empty object where you need to pass database as second argument as its what your routes/index.js export function expects.

PFB updated server.js :

const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const bodyParser = require('body-parser');

const db = require('./config/db');
    
const app = express();

const port = 8000;

app.use(bodyParser.urlencoded({extended:true}));

MongoClient.connect(db.url,(err,database) =>{

    if (err) return console.log(err)
    //require('./app/routes')(app,{});
    //check below line changed
     require('./app/routes')(app, database);
    app.listen(port,() => {
        console.log("We are live on"+port); 
    });

});

Solution 7 - node.js

I ran into the same issue. It looks like the mongodb driver module for node was updated since the video was created. I found the code below in the docs which works.

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

var url = 'mongodb://localhost:27017/<dbName>';
MongoClient.connect(url, (err, db) => {
   db.collection('<collection-name>').find({}).toArray(function(err, docs) {

    // Print the documents returned
    docs.forEach(function(doc) {
        console.log(doc);
    });

    // Close the DB
    db.close();
    });

});  

is replaced with

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

  var url = 'mongodb://localhost:27017'; // remove the db name.
    MongoClient.connect(url, (err, client) => {
       var db = client.db(dbName);
       db.collection('<collection-name>').find({}).toArray(function(err, docs) {
    
        // Print the documents returned
        docs.forEach(function(doc) {
            console.log(doc);
        });
    
        // Close the DB
        client.close();
        });
    
    });  

Here is a link to the latest docs in case we run into further syntax issues.

Solution 8 - node.js

For the recent version I was using "mongodb": "^3.1.3" Below code solved my issue

in server.js

MongoCLient.connect(db.url,(err,client)=>{
    var db=client.db('notable123');
    if(err){
    return console.log(err);
    }
    require('./server-app/routes')(app,db);
    app.listen(port, ()=> {
        console.log("we are live on : "+ port);
    })

})

and your post code is like

module.exports = function(app,db) {
    app.post('/notes',(req,res)=>{
        const note= {text: req.body.body,title:req.body.title};
        db.collection('notes').insertOne(note,(err,result)=>{
            if(err) {
                res.send({"error":"Ann error has occured"}); 
            } else {
                res.send(result.ops[0])
            }
        });
    });
};

Solution 9 - node.js

module.exports = function(app, db) {
  app.post('/notes', (req, res) => {
  const note = { text: req.body.body, title: req.body.title };
  db.collection('notes').insert(note, (err, result) => {
...

db -> client

module.exports = function(app, client) {
  var db = client.db("name");
  app.post('/notes', (req, res) => {
  const note = { text: req.body.body, title: req.body.title };
  db.collection('notes').insert(note, (err, result) => {
...

Solution 10 - node.js

Thanks a lot to Dilum Darshana! Your advice helped a lot. I just want to add, that, if you use promises it will looks like this:

let db;
MongoClient.connect('mongodb://localhost/collectionName').then(connection => {
	db = connection.db('collectionName');
	app.listen(3000, () => {
		console.log("App started on port 3000");
	});	
}).catch(error => {
	console.log('ERROR:', error);
});

Solution 11 - node.js

In your package.json.

make sure the following versions look like this:

"nodemon": "^1.12.1"
"mongodb": "^2.2.33"

the above nodemon and mongodb versions work together without any errors. so your package.json should look something like this:

    {
  "name": "myapi",
  "version": "1.0.0",
  "description": "Json Api",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "nodemon server.js"
  },
  "author": "Riley Manda",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.18.2",
    "express": "^4.16.2",
    "mongodb": "^2.2.33"
  },
  "devDependencies": {
    "nodemon": "^1.12.1"
  }
}

dont forget to run npm install after downgrading

Solution 12 - node.js

Had this issue as well, I was following a tutorial in which the presenter was using the collection as a function. It never worked for me. What I discovered was that the presenter was using version 2.3.4 of the mongodb npm module. the module is well into version 3.x.x now. When I changed the package.json file to request the 2.x.x version of the mogodb npm module, suddenly everything worked.

What I believed happened was that the module was altered to change the collection into a different object. Don't know how to use the new version but if you specify that you want the 2.x.x version, the old way should work. Specifically I can confirm that (coming from my package.json file, "dependencies" section) "mongodb": "^2.2.31" works.

Best way:

$> npm install mongodb@2.2.31 --save

Solution 13 - node.js

MongoClient.connect(db.url,(err,database) =>{
    if (err) return console.log(err)
    //require('./app/routes')(app,{});
    //try this 
     require('./app/routes')(app,database);
    app.listen(port,() => {
        console.log("We are live on"+port); 
    });
})

here you have to include the database in the empty {}.

or

you can also try installing mongodb to latest which will solve the issue.

npm install mongodb@2.2.33 --save 

else npm install add dependency of "mongodb": "^2.2.33" in node modules.

Solution 14 - node.js

Working code using:

npm version 6.0.1,
Node version 10.1.0
"body-parser": "^1.18.3",
"express": "^4.16.3",
"mongodb": "^3.1.0-beta4"
"nodemon": "^1.17.4"

Here is server.js code:

const express       = require('express');
const MongoClient   = require('mongodb').MongoClient;
const bodyParser    = require('body-parser');
const db            = require('./config/db');
const app           = express();
const port          = 8000;

app.use(bodyParser.urlencoded({ extended:true }))
MongoClient.connect(db.url, { useNewUrlParser: true },  (err, client)=>{
    var db = client.db('notable');
    if (err) return console.log(err)

    require('./app/routes')(app, client);
    app.listen(port,()=>{
        console.log('we are live at '+ port);
    });
})

Here is config/db.js code:

module.exports = {
    url:"mongodb://127.0.0.1:27017"
}

Here is routes/note_routes.js:

 var ObjectId = require('mongodb').ObjectID;
 module.exports= function (app, client) {
        var db = client.db('notable');
        //find One
        app.get('/notes/:id', (req, res)=>{
                const id =req.params.id;
                const details ={'_id': new ObjectId(id)}
                db.collection('notes').findOne(details, (err, item)=>{
                    if(err)
                    {
                        res.send({'error':"An error has occured"})
                    }
                    else
                    {
                        res.send(item)
                    }
                });
            });
            //update rout
            app.put('/notes/:id', (req, res)=>{
                const id =req.params.id;
                const details ={'_id': new ObjectId(id)}
                const note ={text: req.body.body, title: req.body.title};
                db.collection('notes').update(details, note, (err, item)=>{
                    if(err)
                    {
                        res.send({'error':"An error has occured"})
                    }
                    else
                    {
                        res.send(item)
                    }
                });
            });

            //delete route
            app.delete('/notes/:id', (req, res)=>{
                const id =req.params.id;
                const details ={'_id': new ObjectId(id)}
                db.collection('notes').remove(details, (err, item)=>{
                    if(err)
                    {
                        res.send({'error':"An error has occured"})
                    }
                    else
                    {
                        res.send("Note "+id+"deleted!")
                    }
                });
            });
            //insert route
            app.post('/notes', (req, res)=>{
                const note ={text: req.body.body, title: req.body.title};
                db.collection('notes').insert(note, (err, results)=>{
                    if(err)
                    {
                        res.send({'error':"An error has occured"})
                    }
                    else
                    {
                        res.send(results.ops[0])
                    }
                });
    
            });
        };

Solution 15 - node.js

Dont use database name in connection url:

const mongo_url = 'mongodb://localhost:27017'

Instead use below method:

MongoClient.connect(mongo_url , { useNewUrlParser: true }, (err, client) => {
        if (err) return console.log(err)
        const  db =  client.db('student')
        const collection = db.collection('test_student');
        console.log(req.body);
        collection.insertOne(req.body,(err,result)=>{
            if(err){
                res.json(err);
            }
            res.json(result);
        });
    });

Solution 16 - node.js

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

//connection url

 const url = 'mongodb://localhost:27017/myproject';

 MongoClient.connect(url,{useNewUrlParser: true},(err,client)=> {
  if(err) {
    return console.dir(err)
  }

   console.log('Connected to MongoDB')

  //get the collection
  let db = client.db('myproject');
  db.collection('users').insertOne({
  name: 'Hello World',
  email: '[email protected]'

  },(err,result)=> {
  if(err) {
      return console.dir(err)
  }
  console.log("Inserted Document");
  console.log(result);
 
     });
   });

Solution 17 - node.js

I've simple solution:

note_routes.js

db.collection('notes').insert(note, (err, result) => {

replace

db.db().collection('notes').insert(note, (err, result) => {

Solution 18 - node.js

I am doing the same tutorial having the same issue. I just checked all the answers and found the one for me.

MongoClient.connect(db.url, { useUnifiedTopology: true }, (err, client) => {
var database = client.db('test');
if (err) return console.log(err) 
require('./app/routes')(app, database);
app.listen(port, () => { console.log('We are live on ' + port);}); })

changed database to client and define the database as client.db('test')

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJayView Question on Stackoverflow
Solution 1 - node.jsJake BoomgaardenView Answer on Stackoverflow
Solution 2 - node.jsantikytheratonView Answer on Stackoverflow
Solution 3 - node.jsShashi KiranView Answer on Stackoverflow
Solution 4 - node.jsDilum DarshanaView Answer on Stackoverflow
Solution 5 - node.jsNaveen Kumar VView Answer on Stackoverflow
Solution 6 - node.jsMihir BhendeView Answer on Stackoverflow
Solution 7 - node.jsPulkit AggarwalView Answer on Stackoverflow
Solution 8 - node.jsKrishView Answer on Stackoverflow
Solution 9 - node.jsYong-bin JeongView Answer on Stackoverflow
Solution 10 - node.jsAlexandr ShmidtView Answer on Stackoverflow
Solution 11 - node.jsRileyMandaView Answer on Stackoverflow
Solution 12 - node.jsPhiipTView Answer on Stackoverflow
Solution 13 - node.jsShashidhar ReddyView Answer on Stackoverflow
Solution 14 - node.jsSanaullah AhmadView Answer on Stackoverflow
Solution 15 - node.jsRavi JaisawalView Answer on Stackoverflow
Solution 16 - node.jsTikaram MardiView Answer on Stackoverflow
Solution 17 - node.jsDmitrii DubrovinView Answer on Stackoverflow
Solution 18 - node.jsuser12163021View Answer on Stackoverflow