Db.collection is not a function when using MongoClient v3.0
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:UsersuserDesktopWeb ProjectWebService.JS:79:14
at args.push (c:Usersusernode_modulesmongodblibutils.js:431:72)
at c:Usersusernode_modulesmongodblibmongo_client.js:254:5 at connectCallback (c:Usersusernode_modulesmongodblibmongo_client.js:933:5) at c:Usersusernode_modulesmongodblibmongo_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.
In your package.json, you should change the MongoDB line to "MongoDB": "^2.2.33". You will need to uninstall MongoDB; then npm install to install this version.
This has solved the issue for me. Seems to be a bug or docs need to be updated. However, 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();
});
});