1

I am trying to simply insert an entry in a MongoDB collection using Nodejs. Here is my code:

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');

  db.collection('Todos').insertOne({
    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));
  });

  db.close();
});

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

error:

TypeError: db.collection is not a function
Dilip
  • 2,622
  • 1
  • 20
  • 27
Soumik Rakshit
  • 859
  • 9
  • 22

3 Answers3

6

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 .... 
Przemek eS
  • 1,224
  • 1
  • 8
  • 21
2

you can rewrite your code as follow

MongoClient.connect(url,(err,db) =>{ 
  const database= db.db('TodoApp')
  database.collection('Todos').insertOne({})
}
edkeveked
  • 17,989
  • 10
  • 55
  • 93
1

The reason for this error is the version of the NodeJs Driver. TypeError: db.collection is not a function. If the version is > 3.0.1 then you have to change the db to client. For more info check this page, it helped me! [db.collection is not a function when using MongoClient v3.0

Hope that helps!

Mariana
  • 349
  • 3
  • 18