Hello! I am a beginner. I recently started node.js tutorial on w3schools on node.js. I stumbled on the place where I have to connect to mongodb. So, I created my project folder, changed to it, ran npm init, installed mongodb. Then I had to create a .js file with the following content:
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/mydb";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
console.log("Database created!");
db.close();
});
But when I run it, the black cursor moves on a new line in the terminal and blinks for several seconds. It just hangs there and I get no error messages nor command prompt. After a few minutes I choose to Ctrl+C to stop it. I tried to use 127.0.0.1 instead of localhost, but that didn’t work either.
So, I started to read the doc on mongodb.com, which suggests using this code:
const { MongoClient, ServerApiVersion } = require("mongodb");
// Replace the placeholder with your Atlas connection string
const uri = "mongodb://localhost:27017";
// Create a MongoClient with a MongoClientOptions object to set the Stable API version
const client = new MongoClient(uri, {
serverApi: {
version: ServerApiVersion.v1,
strict: true,
deprecationErrors: true,
}
}
);
async function run() {
try {
// Connect the client to the server (optional starting in v4.7)
await client.connect();
// Send a ping to confirm a successful connection
await client.db("admin").command({ ping: 1 });
console.log("Pinged your deployment. You successfully connected to MongoDB!");
} finally {
// Ensures that the client will close when you finish/error
await client.close();
}
}
run().catch(console.dir);
I am not aware of what all of this code does but at least it prints that it successfully connected and there is command prompt after running it.
I start my server by running: sudo systemctl start mongod
I can check that it is running by: sudo systemctl status mongod
I use Debian 11
I have mongosh installed, it says:
`Connecting to: mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+1.10.1
Using MongoDB: 6.0.8
Using Mongosh: 1.10.1
For mongosh info see: https://docs.mongodb.com/mongodb-shell/
`
My question is firstly what is wrong with the w3schools tutorial code? I could take the latter from mongodb docs but it looks bulky. I wanted to start small and I just can’t get why it doesn’t work. Thanks.