Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4072 pages
Node.js, PHP and APIs

mongoose.connect() receives undefined because the connection string env var is empty

Errormongoose.connect(), first argument should be String, received undefined

Short answer

The value you pass to mongoose.connect() comes from process.env, and that variable is empty when the call runs. Either the .env file was not loaded yet, was looked up in the wrong working directory, or Node.js was never told about it. Load it first, or start Node.js with --env-file.

  • Applies to Mongoose 8, Node.js 22, dotenv 16
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Fix it fast

  1. 1Find out which cause you have

    Print the variable on the first line of your entry file, before any import that uses it. If it prints undefined there, the problem is the loading step, not Mongoose.

    node -e "console.log(process.env.MONGO_URI)"
  2. 2Match what you see, then jump to its fix

    1. 1The app works when started from the project root and fails from a test runner, a script folder or a monorepo packagedotenv looks for .env in the wrong directoryFix
    2. 2The project uses import statements, and the config() call is in the same file as the connect callWith ES modules, dotenv runs after the code that reads the variableFix
    3. 3No dotenv in the project, and the variable is only defined inside a .env fileNode.js is never told to load the env fileFix

What does the error look like?

  • mongoose.connect(), first argument should be String, received undefined
  • process.env.MONGO_URI is undefined only when the app or tests are started a certain way

Cause 1 of 3

dotenv looks for .env in the wrong directory

1Check

dotenv reads .env from the current working directory, which is where the process was launched, not where the script file sits.

pwd
ls -a | grep "^.env"

2Fix

Start the process from the folder that holds .env, or pass an explicit path.

require('dotenv').config({ path: require('path').join(__dirname, '..', '.env') });

3Verify

The variable prints a connection string.

node -e "require('dotenv').config(); console.log(typeof process.env.MONGO_URI)"

Confirmed by github.com

Did this fix it?

Cause 2 of 3

With ES modules, dotenv runs after the code that reads the variable

1Check

In ES modules, imported files are evaluated before the body of the importing file, so config() placed in that body can run too late.

grep -rn "dotenv" src package.json

2Fix

Import dotenv/config as the first import, or load it before the module that reads the variable.

import 'dotenv/config';
import mongoose from 'mongoose';

await mongoose.connect(process.env.MONGO_URI);

3Verify

The first connection attempt gets a string.

node src/index.js

Confirmed by github.com

Did this fix it?

Cause 3 of 3

Node.js is never told to load the env file

1Check

Node.js does not read .env on its own. Since v20.6.0 it can load one with --env-file, resolved against the current directory, and it throws if the file does not exist.

node -v && ls -a | grep "^.env"

2Fix

Add the flag to the start command, or use --env-file-if-exists (Node.js 22.9.0 and later) when the file is optional.

node --env-file=.env src/index.js

3Verify

The app starts and Mongoose connects.

node --env-file=.env -p "typeof process.env.MONGO_URI"

Confirmed by nodejs.org

Did this fix it?

How do I stop it coming back?

  • Fail fast: check the variable at startup and throw a clear message when it is missing.
  • Use 127.0.0.1 instead of localhost in local connection strings; Mongoose documents that Node.js 18 and later may resolve localhost to IPv6.
  • Use one loading method per project, and put it first in the entry file.

Sources

How was this page made?

I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.

Which stack is behind this page?

Projects of mine built on the same technologies:

Related fixes

Back end

ng serve says it cannot determine the project or target

Cannot determine project for command.

The Angular CLI looked through angular.json for a project that defines the target you asked for (serve, build, test) and found none, or found several and could not pick one.

3 causes, each with a fix

Back end

ng serve cannot find the dev-server builder package

Could not find the implementation for builder @angular/build:dev-server

The builder named in angular.json (for example @angular-devkit/build-angular:dev-server) is looked up as an npm package starting from the workspace root.

3 causes, each with a fix

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.