node.jsexpressmongoosenodemon

nodemon connects to database, node server.js does not


When I wanted to deploy my app on Heroku, I made a strange discovery: When I start the server with "nodemon", the connection to the database works perfectly. If I use "node server.js" instead, no connection to the database is established. I actually thought that both commands do the same thing, except that thanks to nodemon you don't have to restart the server after every change.

Does anyone know this problem and how to fix it? Many thanks in advance!

My techstack: Angular 14.3, Node 20.11, Express 4.17.1, Mongoose 8.2.3

Here is the error:

Connection to database failed! MongoServerError: bad auth : authentication failed
    at Connection.sendCommand (C:\Users\torbe\Documents\my-music-theory\backend\node_modules\mongodb\lib\cmap\connection.js:281:27)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async Connection.command (C:\Users\torbe\Documents\my-music-theory\backend\node_modules\mongodb\lib\cmap\connection.js:304:26)
    at async continueScramConversation (C:\Users\torbe\Documents\my-music-theory\backend\node_modules\mongodb\lib\cmap\auth\scram.js:131:15)
    at async executeScram (C:\Users\torbe\Documents\my-music-theory\backend\node_modules\mongodb\lib\cmap\auth\scram.js:80:5)
    at async performInitialHandshake (C:\Users\torbe\Documents\my-music-theory\backend\node_modules\mongodb\lib\cmap\connect.js:101:13)
    at async connect (C:\Users\torbe\Documents\my-music-theory\backend\node_modules\mongodb\lib\cmap\connect.js:19:9) {
  errorResponse: {
    ok: 0,
    errmsg: 'bad auth : authentication failed',
    code: 8000,
    codeName: 'AtlasError'
  },
  ok: 0,
  code: 8000,
  codeName: 'AtlasError',
  connectionGeneration: 0,
  [Symbol(errorLabels)]: Set(2) { 'HandshakeError', 'ResetPool' }
}

This is my package.json:

{
  "name": "backend",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "engines": {
    "node": "20.x"
  },
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node server.js"
  },
  "author": "Torben Jan Müller",
  "license": "ISC",
  "dependencies": {
    "express": "^4.17.1",
    "mongoose": "^8.2.3",
    "mongoose-unique-validator": "^5.0.0",
    "nodemon": "^2.0.12",
    "request-ip": "^3.3.0"
  },
  "devDependencies": {
    "@types/request-ip": "0.0.38"
  }
}


Solution

  • The problem was caused by the environment variable in the server.js file. It was stored in the nodemon.js file and therefore could not be found when the server was started with "node server.js". The environment variable is now stored in a .env file, the database is connected and deploying to Heroku also works perfectly.

    Install dotenv

    npm i dotenv
    

    server.js

    require('dotenv').config();
    
    const connectToDatabase = async () => {
        try {
            await mongoose.connect("mongodb+srv://<username>:" + process.env.MONGO_ATLAS_PW + "@<cluster>.mongodb.net/<collection>?retryWrites=true&w=majority");
            console.log('Connected to database!');
        } catch (err) {
            console.log('Connection to database failed!', err);
        }
    }
    
    connectToDatabase();
    

    Create a .env file in root and include the environment variables

    MONGO_ATLAS_PW = "password"