I am a starter of React. I am trying to connect React back-end app with local mongodb. I have imported MongoClient from mongodb. However, I cannot use app.get to get connect with local mongodb using following code:
app.get('/api/articles/:name', async (req, res) => {
try
{
const articleName = req.params.name;
const client = await MongoClient.connect('mongodb://localhost:27017', { useNewUrlParser: true});
const db = client.db('my-blog');
const articleInfo = await db.collection('articles').findOne({ name: articleName })
res.status(200).json(articleInfo);
client.close();
}
catch (error) {
res.status(500).json({'msg': 'Error connecting to db', error});
}
})
The error likes
{
"msg": "Error connecting to db",
"error": {
"reason": {
"type": "Unknown",
"servers": {},
"stale": false,
"compatible": true,
"heartbeatFrequencyMS": 10000,
"localThresholdMS": 15
}
}
}
However, it works when I edit the client command likes
const client = await MongoClient.connect('mongodb://127.0.0.1:27017', { useNewUrlParser: true});
What is the difference between using localhost and 127.0.0.1. Shouldn't these two same? Thanks
I use Mongo 5.0.9