Connect TypeScript Node.js and Mongoose With Environment Variables

04/18/20191 Min Read — In TypeScript, Node.js

In your existing project, add mongoose, dotenv, and @types/mongoose:

yarn add mongoose dotenv
yarn add @types/mongoose --dev

Set up your database, for example with MongoDB Atlas or on your local machine.

Create a new file called .env and add your MongoDB connection string.

MONGO_URI=mongodb+srv://<your-user-name>:<your-password>@whatever.mongodb.net/test?retryWrites=true

Now you can connect mongoose with Node.js inside server.ts.

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

mongoose.connect(`${process.env.MONGO_URI}`, { useNewUrlParser: true })

Please note, you have to use a template string and interpolate the environment variable.

Otherwise, you'll get an error:

Argument of type 'string | undefined' is not assignable to parameter of type 'string'.  Type 'undefined' is not assignable to type 'string'

So, this code works in JavaScript, but not in Typescript:

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

+ mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true })
- mongoose.connect(`${process.env.MONGO_URI}`, { useNewUrlParser: true })

Further Reading