I am following W3Schools.com’s ‘Node.js MongoDB’ tutorial. My action.js file contains the following code:
var mongo = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/mydb";
mongo.connect(url, function (err, db) {
if (err) throw err;
console.log("Database created!");
db.close();
});
When I try to run the file using node action.js
, nothing happens. Even after going through several forums I can’t figure out what is going on.
This is the same question but at least that person is getting some error, which I’m not.
Terminal screenshot after executing Node.js command
mongod --version
db version v8.0.1
Build Info: {
"version": "8.0.1",
"gitVersion": "fcbe67d668fff5a370e2d87b9b1f74bc11bb7b94",
"modules": [],
"allocator": "tcmalloc-gperf",
"environment": {
"distmod": "windows",
"distarch": "x86_64",
"target_arch": "x86_64"
}
}
mongosh --version
2.3.2
I tried changing the //localhost:27017
to 127.0.0.1:27017
as lots of other solutions have mentioned but it didn’t make any difference.
2
Answers
Try instead this script which works:
Did you start the server mongodb before all?
Below is the string to start the server on my linux machine
sudo mongod –noauth –port 27017 –dbpath /var/lib/mongodb