Implementation of an Express server with MongoDB MongoClient

Issue

I’m new with both of these technologies and really need help.

I have MongoDB set up on my computer and I have mongod running.
I have a database called ‘memories-db’ & a collection called ‘entries’, I can run mongosh in a different terminal and am able to get this output from

db.entries.find()
[
  {
    _id: ObjectId("62e81903809f6ae89c864a4d"),
    id: 201901011245,
    upvotes: 0,
    comments: []
  },
  {
    _id: ObjectId("62e81903809f6ae89c864a4e"),
    id: 202001011246,
    upvotes: 0,
    comments: []
  },
  {
    _id: ObjectId("62e81903809f6ae89c864a4f"),
    id: 202201011247,
    upvotes: 0,
    comments: []
  },
  {
    _id: ObjectId("62e81903809f6ae89c864a50"),
    id: 201401011248,
    upvotes: 0,
    comments: []
  }
]

I have an Express server defined as

// Boilerplate
// Import express & its types
import express, { Express, Request, Response } from 'express'

// MongoDB
// Import MongoClient & MongoDB types
import { MongoClient, Db, Collection, WithId, Document } from 'mongodb'

// Constant to store express object
const app: Express = express()
// Constant to store MongoDB URI
const mongoURI: string = 'mongodb://localhost:27017'
// Constant to store port number to listen on
const port: number = 8000

// GET Routes
app.get(
    '/api/entries/:entryId',
    (req: Request, res: Response) => {
        const entryId: number = +req.params.entryId

        MongoClient.connect(
            mongoURI,
            {},
            async (error, client) => {
                if (error || !client)
                    res.status(500).json({ message: 'Error connecting to db', error })

                else {  
                    const db: Db = client.db('memories-db')

                    const entryInfo: WithId<Document> | null = await db.collection('entries').findOne({ id: entryId })

                    res.status(200).json(entryInfo)

                    client.close()
                }
            }
        )
    }
)

app.listen(
    port,
    () => {
        console.log(`⚡️[server]: Server is running at http://localhost:${port}`)
    }
)

But when I make GET request I always get an error, please tell me what I’m doing wrong

{
    "message": "Error connecting to db",
    "error": {
        "reason": {
            "type": "Unknown",
            "servers": {},
            "stale": false,
            "compatible": true,
            "heartbeatFrequencyMS": 10000,
            "localThresholdMS": 15
        }
    }
}

Solution

It turns out that my PC wasn’t resolving the local MongoDB URI properly.
So, replacing

'mongodb://localhost:27017'

to

'mongodb://127.0.0.1:27017'

fixed the issue

Answered By – Devansh Das

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published