Getting error when hitting a post request to mongoDB compass database

Amritpal Singh 60 Reputation points
2023-07-26T18:39:28.4066667+00:00

I am getting an error when try to hit the post request on the MongoDB tool . I have a created a new Database over there and trying the post the data over there . Just to make sure it is connecting with the MongoDB compass or not. The error I am getting in terminal of vs code :

Error saving user: Operation `users.insertOne()` buffering timed out after 10000ms
C:\Users\asvar\Desktop\ReactJsHarry\inotebook\backend\node_modules\mongoose\lib\connection.js:788
    err = new ServerSelectionError();
          ^

MongooseServerSelectionError: connect ECONNREFUSED ::1:27017
    at _handleConnectionErrors (C:\Users\asvar\Desktop\ReactJsHarry\inotebook\backend\node_modules\mongoose\lib\connection.js:788:11)
    at NativeConnection.openUri (C:\Users\asvar\Desktop\ReactJsHarry\inotebook\backend\node_modules\mongoose\lib\connection.js:763:11) {
  reason: TopologyDescription {
    type: 'Unknown',
    servers: Map(1) {
      'localhost:27017' => ServerDescription {
        address: 'localhost:27017',
        type: 'Unknown',
        hosts: [],
        passives: [],
        arbiters: [],
        tags: {},
        minWireVersion: 0,
        maxWireVersion: 0,
        roundTripTime: -1,
        lastUpdateTime: 597047601,
        lastWriteDate: 0,
        error: MongoNetworkError: connect ECONNREFUSED ::1:27017
            at connectionFailureError (C:\Users\asvar\Desktop\ReactJsHarry\inotebook\backend\node_modules\mongodb\lib\cmap\connect.js:367:20)
            at Socket.<anonymous> (C:\Users\asvar\Desktop\ReactJsHarry\inotebook\backend\node_modules\mongodb\lib\cmap\connect.js:290:22)
            at Object.onceWrapper (node:events:628:26)
            at Socket.emit (node:events:513:28)
            at emitErrorNT (node:internal/streams/destroy:151:8)
            at emitErrorCloseNT (node:internal/streams/destroy:116:3)
            at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
          cause: Error: connect ECONNREFUSED ::1:27017
              at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1494:16) {
            errno: -4078,
            code: 'ECONNREFUSED',
            syscall: 'connect',
            address: '::1',
            port: 27017
          },
          [Symbol(errorLabels)]: Set(1) { 'ResetPool' }
        },
        topologyVersion: null,
        setName: null,
        setVersion: null,
        electionId: null,
        logicalSessionTimeoutMinutes: null,
        primary: null,
        me: null,
        '$clusterTime': null
      }
    },
    stale: false,
    compatible: true,
    heartbeatFrequencyMS: 10000,
    localThresholdMS: 15,
    setName: null,
    maxElectionId: null,
    maxSetVersion: null,
    commonWireVersion: 0,
    logicalSessionTimeoutMinutes: null
  },
  code: undefined
}

response I am getting :

{
  "error": "Error saving user"
}

and post request url : https://localhost:3000/api/auth
auth.js under routes folder :

// auth.js
const express = require('express');
const router = express.Router();
const User = require('../models/User');

// Create a user using POST: "/api/auth". Doesn't require Auth
router.post('/', async (req, res) => {
  try {
    console.log(req.body);
    const user = new User(req.body);
    await user.save();
    res.send(user);
  } catch (error) {
    console.error('Error saving user:', error.message);
    res.status(500).json({ error: 'Error saving user' });
  }
});

module.exports = router;

User.js under modules folder:

const mongoose = require('mongoose')
const Schema = mongoose.Schema

const UserSchema = new Schema({
    name: {
        type: String,
        required: true
    },
    email: {
        type: String,
        required: true,
        unique: true
    },

    password: {
        type: String,
        required: true
    },
    date: {
        type: Date,
        default: Date.now
    },
})

module.exports = mongoose.model('user',UserSchema)

index.js:

const connectToMongo = require('./db')
const express = require('express')


connectToMongo()

const app = express()
const port = 3000

app.use(express.json());

app.use('/api/auth',require('./routes/auth'))
app.use('/api/notes',require('./routes/notes'))

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

db.js:

const mongoose = require('mongoose')

const mongoURI = "mongodb://localhost:27017/AmritData"

const connectToMongo = () => {
   mongoose.connect(mongoURI)
   console.log("Connect to MongoDB successfully")
}
module.exports = connectToMongo

Why I am getting these errors ?

JavaScript API
JavaScript API
An Office service that supports add-ins to interact with objects in Office client applications.
942 questions
0 comments No comments
{count} votes