mongoose.connect() receives undefined because the connection string env var is empty
mongoose.connect(), first argument should be String, received undefinedShort 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.
Fix it fast
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)"2Match what you see, then jump to its fix
- 1
The 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
The 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
No dotenv in the project, and the variable is only defined inside a .env fileNode.js is never told to load the env fileFix
- 1
What does the error look like?
mongoose.connect(), first argument should be String, received undefinedprocess.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
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.json2Fix
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.jsConfirmed by github.com
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.js3Verify
The app starts and Mongoose connects.
node --env-file=.env -p "typeof process.env.MONGO_URI"Confirmed by nodejs.org
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
Node.js cannot connect to MongoDB: ECONNREFUSED on port 27017
MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017
ECONNREFUSED means nothing accepted the connection at that address and port.
4 causes, each with a fixBack 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 fixBack end
ng fails with Cannot find module @angular/cli/bin/ng
Cannot find module '@angular/cli/bin/ng'
The ng command is the entry point to the Angular CLI package.
2 causes, each with a fixBack end
Angular app shows 'Cannot GET /' when served by a Node.js server
Cannot GET /dashboard
Cannot GET / is Express saying no route or file matches the request.
3 causes, each with a fixBack 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 fixBack end
Angular build says it cannot resolve '@angular/localize/init'
Can't resolve '@angular/localize/init' in '/usr/src/app/src'
The build imports @angular/localize, and that package is not in node_modules.
2 causes, each with a fix