Soumik Rakshit Soumik Rakshit - 2 months ago 128
Node.js Question

db.collection is not a function

I am trying to simply insert an entry in a

collection using
. Here is my code:


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

MongoClient.connect('mongodb://localhost:27017/TodoApp', (err, db) => {
if (err) {
return console.log('Unable to connect to MongoDB server');
console.log('Connected to MongoDB server');

text: 'Something to do',
completed: false
}, (err, result) => {
if (err) {
return console.log('Unable to insert todo', err);

console.log(JSON.stringify(result.ops, undefined, 2));


When I run the code, it showing the following error:


TypeError: db.collection is not a function

Answer Source

Uninstalling existing mongodb package and reinstalling using the following commands resolved the issues

npm uninstall mongodb --save
npm install mongodb@2.2.33 --save 

Version MongoDB >= 3 - That database variable is actually the parent object of the object you are trying to access. If u using mongo 3+:

const myDb = db.db('YourDatabase') 
myDb.collection('YourDatabase).insertOne .... 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download