I have been trying W3schools tutorial on nodeJS with MongoDB.
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.
I solved it easily via running these codes:
Happy Coding!
Piggy backing on @MikkaS answer for Mongo Client v3.x, I just needed the async / await format, which looks slightly modified as this:
The only problem with your code is you are accessing the object that's holding the database. You must access the database directly (see database variable above). This code will return your database in an array and then it loops through it and logs the name for everyone in the database.
For those that want to continue using version ^3.0.1 be aware of the changes to how you use the
MongoClient.connect()
method. The callback doesn't returndb
instead it returnsclient
, against which there is a function calleddb(dbname)
that you must invoke to get thedb
instance you are looking for.For people on version 3.0 of the MongoDB native NodeJS driver:
(This is applicable to people with "mongodb": "^3.0.0-rc0", or a later version in package.json, that want to keep using the latest version.)
In version 2.x of the MongoDB native NodeJS driver you would get the database object as an argument to the connect callback:
According to the changelog for 3.0 you now get a client object containing the database object instead:
The
close()
method has also been moved to the client. The code in the question can therefore be translated to:I have MongoDB shell version v3.6.4, below code use mongoclient, It's good for me: