Matt Matt - 5 months ago 59
Node.js Question

TypeError: Cannot read property 'connect' of undefined

'use strict';

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

MongoClient.connect(
'mongodb://127.0.0.1:27017/accounting',
function (err, connection){
var collection = connection.collection('customers');

collection.insert({'name': 'John Doe'}, function(err, count){

collection.find().toArray(function(err, documents){
console.dir(documents);
connection.close();
});

});

});


Getting this error when using this code, I would like to know what is causing the error and any possible fixes.

TypeError: Cannot read property 'connect' of undefined
at Object.<anonymous> (C:\Users\Matt\WebstormProjects\keyword-wrangler\index.js:6:12)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Function.Module.runMain (module.js:441:10)
at startup (node.js:139:18)
at node.js:968:3


Not entirely sure what is causing this, I am using WebStorm and have installed the latest version of mongodb.

Answer

Correct way

var MongoClient = require('mongodb').MongoClient; // it's not a function

Your way

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

Docs

Comments