Soumik Rakshit Soumik Rakshit - 9 months ago 368
Node.js Question

db.collection is not a function

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

Answer Source

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

npm uninstall mongodb --save
npm install [email protected] --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