8

I am trying to connect to MongoDB when starting my node.js server. My server is in src/server.ts, connectDB() is in src/config/db.ts and my .env, and environment.d.ts are in the root directory. However, when trying to connect to the DB it still says my MONGO_URI, declared in .env, is of type string | undefined.

environment.d.ts:

declare namespace NodeJS {
  export interface ProcessEnv {
    PORT?: string;
    NODE_ENV: 'development' | 'production';
    MONGO_URI: string;
  }
}

src/server:

import dotenv from 'dotenv';
import express from 'express';
import connectDB from './config/db';

dotenv.config({ path: '../.env' });
connectDB();
const app = express();

.....

src/config/db.ts:

import mongoose from 'mongoose';

const connectDB = async () => {
  try {
    const conn = await mongoose.connect(process.env.MONGO_URI, {
      useUnifiedTopology: true,
      useNewUrlParser: true,
      useCreateIndex: true,
    });

    console.log(`MongoDB connected: ${conn.connection.host}`);
  } catch (error) {
    console.error(`ERROR: ${error.message}`);
    process.exit(1);
  }
};

export default connectDB;

Full error code:

TSError: ⨯ Unable to compile TypeScript:
src/config/db.ts:5:41 - error TS2769: No overload matches this call.
  Overload 1 of 3, '(uri: string, callback: (err: CallbackError) => void): void', gave the following error.
    Argument of type 'string | undefined' is not assignable to parameter of type 'string'.
      Type 'undefined' is not assignable to type 'string'.
  Overload 2 of 3, '(uri: string, options?: ConnectOptions | undefined): Promise<typeof import("mongoose")>', gave the following error.
    Argument of type 'string | undefined' is not assignable to parameter of type 'string'.
      Type 'undefined' is not assignable to type 'string'.

5     const conn = await mongoose.connect(process.env.MONGO_URI, {

I tried declaring the dotenv.config() within db.ts and removing the path option when declaring it in server.ts. Hovering over the environment variable in VSCode shows (property) NodeJS.ProcessEnv.MONGO_URI: string. So I really thought this was setup right but I must be missing something.

0

2 Answers 2

11

Try to add it inside global.d.ts file like this

declare global {
    namespace NodeJS {
        interface ProcessEnv {
             PORT?: string;
             NODE_ENV: 'development' | 'production';
             MONGO_URI: string;
        }
    }
}

export {};
Sign up to request clarification or add additional context in comments.

2 Comments

This is the solution that worked for me using nextjs
The export {}; is what I was missing.
6

This error may be due to your tsconfig.json file rules. Most probably due to "strictNullChecks": true you may have put this rule to true. There are two simple solutions:

  1. put this rule to false like this "strictNullChecks": false.
  2. Or add ! immediately after process.env.MONGO_URI like this: process.env.MONGO_URI!. The symbol ! insures your typescript transpiler the value will not be undefined.

1 Comment

This does get around the error, but now it still says the parameter I am passing is undefined so I don't know why none of my .env variables are none existent even though I have declared them. Edit: moved my server up to the root and changed the path, works now. Thanks for all your help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.