Back

Explore Courses Blog Tutorials Interview Questions
0 votes
4 views
in Web Technology by (47.6k points)

When I try to implement this example in a nodeJS environment and invoke the function with an AJAX call, I got the error below:

TypeError: db.collection is not a function 

at c:\Users\user\Desktop\Web Project\WebService.JS:79:14 

at args.push (c:\Users\user\node_modules\mongodb\lib\utils.js:431:72) 

at c:\Users\user\node_modules\mongodb\lib\mongo_client.js:254:5 at connectCallback (c:\Users\user\node_modules\mongodb\lib\mongo_client.js:933:5) at c:\Users\user\node_modules\mongodb\lib\mongo_client.js:794:11 at _combinedTickCallback (internal/process/next_tick.js:73:7) 

at process._tickCallback (internal/process/next_tick.js:104:9)

Please find below my implemented code:

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

var url = "mongodb://localhost:27017/mytestingdb";

MongoClient.connect(url, function(err, db) { 

if (err) throw err; 

db.collection("customers").findOne({}, 

function(err, result) { 

if (err) throw err; 

console.log(result.name); 

db.close(); 

}); 

});

Note that the error occurs whenever the execution hits:

db.collection("customers").findOne({}, function(err, result) {}

Also, note (in case it matters) that I have installed the latest MongoDB package for node JS (npm install MongoDB), and the MongoDB version is MongoDB Enterprise 3.4.4, with MongoDB Node.js driver v3.0.0-rc0.

2 Answers

0 votes
by (106k points)

In your package.json, you should change MongoDB line to "MongoDB": "^2.2.33". You will need to npm uninstall MongoDB; then npm install to install this version.

This resolved the issue for me. Seems to be a bug or docs need to be updated.

0 votes
by (108k points)

For 3.0 you get a client object containing the database object:

 

MongoClient.connect('mongodb://localhost:27017', (err, client) => {

  // Client returned

  var db = client.db('mytestingdb');

});

The close() method has been shifted to the client. Thus, the code in the question can be translated to the following:

 

MongoClient.connect('mongodb://localhost', function (err, client) {

  if (err) throw err;

 

  var db = client.db('mytestingdb');

  db.collection('customers').findOne({}, function (findErr, result) {

    if (findErr) throw findErr;

    console.log(result.name);

    client.close();

  });

});

Related questions

Browse Categories

...