Connect MongoDB
Install database packages and configure environment variables.
Goal for this step
Set up MongoDB dependencies, create environment files, and configure Nest so the app can talk to the database.
1. Install MongoDB + validation libraries
npm installthese packages so Nest can talk to MongoDB, validate inputs, and read.envfiles:
npm install @nestjs/mongoose mongoose nestjs-zod zod @nestjs/config@nestjs/mongooseis the Nest bridge for MongoDB.mongooseis the official MongoDB driver.nestjs-zodintegrates Zod with Nest so we can define DTOs using schemas.@nestjs/configloads.envfiles automatically soprocess.envhas the values you just captured.
2. Confirm your .env files
You should already have .env.example and .env.development.local from the Prepare MongoDB step. Double-check they contain the right connection string for the option you chose:
- Docker users keep
USE_ATLAS=falseand rely on the defaultMONGODB_URI. - Atlas users set
USE_ATLAS=trueand paste the long connection string intoMONGODB_URI_ATLAS.
If you skipped the previous page, go back and complete those steps before continuing.
3. Configure AppModule
Edit src/app.module.ts so Nest loads environment files before reading them and falls back sensibly.
import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { MongooseModule } from '@nestjs/mongoose';
@Module({
imports: [
// Module to load environment variables
ConfigModule.forRoot({
isGlobal: true,
envFilePath: ['.env.development.local', '.env'],
}),
// Module to connect to MongoDB
MongooseModule.forRootAsync({
inject: [ConfigService],
useFactory: (config: ConfigService) => {
const useAtlas = config.get<string>('USE_ATLAS') === 'true';
const uri = useAtlas
? config.get<string>('MONGODB_URI_ATLAS')
: config.get<string>('MONGODB_URI');
if (!uri) {
throw new Error('Missing MongoDB URI. Check your .env values.');
}
return { uri };
},
}),
],
controllers: [],
providers: [],
})
export class AppModule {}Why forRootAsync?
process.env is evaluated when the file loads, which happens before ConfigModule.forRoot() runs. Wrapping Mongoose in forRootAsync ensures the config service has already loaded your .env values when we compute the URI.
For now the module only connects to MongoDB. Later pages will add new modules and controllers.
With MongoDB running and AppModule wired up (including the config loader), you are ready to create schemas. Continue to Model to define the Task collection.
Commit your AppModule changes
Before pushing, capture the configuration updates you just made:
git add src/app.module.ts
git commit -m "feat: configure mongodb connection"Push your branch and open a pull request
Stay on your feature/environment-config branch and push it to GitHub:
git push -u origin feature/environment-configThen open a pull request targeting main. Add a short summary (what changed, any screenshots of .env samples) and request a teammate review. When reviewers approve, choose Squash and merge so the entire branch becomes a single commit on main (for example, feat: configure environment & mongodb).
Once merged, pull the latest main locally before starting the next chapter.