I am coding along a tutorial and I am stuck at connecting MongoDB to Express. I successfully installed MongoDB (Mongo Compass and Mongo shell) and I was able to play around with it a little bit to familiarize myself with it. I am using a Windows 10 computer. I was able to create a database and add some documents and collections to it via the mongo shell and cmd prompt.
For the React app I am building, I am using VS Code as the IDE. VS Code is running on Ubuntu (WSL 2) and I cannot connect my app to the database. I have even tried using the MongoDB VS Code extension, but I still cannot connect to the databases available on compass. The Atlas clusters seem to connect just fine.
Below I am including screen grabs of the VS Code and Compass in case someone notices something off.
Here is the code where I try the connection. I have tested out the output on postman, but I am not getting any output in return. The server is running according to nodemon and the app crashes every time I run the get command on postman.
import express from "express";
import { MongoClient } from "mongodb"; //connects to the db
const app = express();
app.use(express.json()); // middleware to enable posting json
app.get('/api/articles/:name', async (req, res) => {
const { name } = req.params;
const client = new MongoClient('mongodb://127.0.0.1:27017');
await client.connect();
const db = client.db('react-blog-db');
const article = await db.collection('articles').findOne({ name });
res.json(article);
});
I have tried some of the options highlighted here, but none of them work for me.
2
Answers
I usually use morgan and mongoose for mongoDB, I know when using mongoose you have to specify the database in your URL string, I would try
You should use your IPv4 address.
will become.
note that "192.168.100.5" will be different for you. You can get it using ipconfig command in cmd.