How can I fix error MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017?

Hello,

How can I fix the MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017 when I added the JSON for http://127.0.0.1:5000/v1/auth/register in postman?

This is the JSON:

{
    "name": "john",
    "password": "secret",
    "email": "john@gmail.com"
}

Here’s my User model:

import mongoose from 'mongoose';
import validator from 'validator';
 
const UserSchema = new mongoose.Schema({
  role: {
    type: String,
    trim: true,
    maxlength: 20,
    default: 'admin',
  },
  name: {
    type: String, 
    required: [true, 'Please provide name'], 
    minlength: 3, 
    maxlength: 20,
    trim: true,
  },
  email: {
    type: String,
    required: [true, 'Please provide email'],
    validate: {
      validator: validator.isEmail,
      message: 'Please provide a valid email',
    },
    unique: true,
  },
  password: {
    type: String,
    required: [true, 'Please provide password'],
    minlength: 6,
    select: false,
  },
  lastName: {
    type: String,
    trim: true,
    maxlength: 20,
    default: 'lastName',
  },
  location: {
    type: String,
    trim: true,
    maxlength: 20,
    default: 'Tacloban City',
  },
});
 
export default mongoose.model('User', UserSchema);

Then my authController.js

import User from '../models/User.js';
 
const register = async (req, res) => {
  try {
    const user = await User.create(req.body);
    res.status(201).json({user});
  } catch (error) {
    res.status(500).json({msg: 'there was an error'});
  }
};
const login = async (req, res) => {
  res.send('login user');
};
const updateUser = async (req, res) => {
  res.send('updateUser');
};
 
export{register, login, updateUser};
1 Like

Sorry if you already did this, but in case you didn’t: can you connect to the database locally, using the mongosh? Also, Is it a replica set ? because mongoose also requires a few options.

If you can include how you’re connecting using mongoose odm (the mongoose.connect statement)

Here is my mongoose script:

import mongoose from 'mongoose';

const connectDB = (url) => {
  return mongoose.connect(url);
};

export default connectDB;

Then the .env

PORT=5000
MONGO_URL=mongodb://127.0.0.1:27017/db_ras

@Jumar_Juaton

That looks fine to me as long as you remember .connect() method returns a promise, and errors should be caught.

I’m no specialist, but I’d do the following checks:

  1. ps -ef | grep [Mm]ongod to check if process is running.
  2. Also/Alternatively ss -l | grep [Mm]ongod to see which socket it is listening on.
  3. Can you connect issuing mongo in the command line, or what is the error?

May also be good to know which platform are you running the server.

The process is running, but I need to run it using npm run start on root dir of the project. I’ve tried running mongod and npm run start on root dir of the project, or even just mongod but it does return 500 error on postman. It only returns the MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017 error if I run npm run start on root dir.

Here’s the complete repo of my code: https://github.com/jumarjuaton/repo-test

@Jumar_Juaton

It’d be better if you share the output to see if the process is running. I send the data as JSON because afaik you’re not processing urlencoded bodies.

This is what I tested and the code runs. This is the request I run using linux lwp-request (alias POST):

echo '{
"name":"santi",
"password":"123Santi",
"email":"hello@pm.me"}' | POST http://localhost:5000/api/v1/auth/register \ 
-c 'application/json' \
-SE -t 3s

And got

201 Created

{
"user":{
"role":"admin",
"name":"santi",
"email":"hello@pm.me",
"password":"123Santi",
"lastName":"lastName",
"location":"Tacloban City",
"_id":"61ef18d9f053c87d81cd9937","__v":0}}

I did minor modifications to the server, because of:

  • listening twice,
  • and logged the error from your register (add a console.log(error) in your code).

It’s as much as I can say with the data you provide. The is the server.js last lines are now:

const port = process.env.PORT || 5000;

/*
app.listen(port, () => {
  console.log(`Server is listening on port ${port}...`)
});
*/

const start = async () => {
    await connectDB(process.env.MONGO_URL);
    app.listen(port, () => {
      console.log(`Server is listening on port ${port}...`);
    });
};

start().catch(e=>console.log(e))

@Jumar_Juaton did you find a solution to this error? I am facing the same error when testing my restapi on Postman. I can send a simple POST request to the serve.