Cannot connect to mongodb using typescript

It is the first time I am using typescript. I have the following connectDb:

import mongoose from "mongoose";

export const dbConnect = async ()=>{
    try{
        const conn = await mongoose.connect(process.env.MONGO_URL);
        console.log(`MongoDb connected: ${conn.connection.host}`.cyan.underline);
    }
    catch(error){
        console.log(error)
        process.exit(1);
    }
}

I get the following error:

The string | argument undefined" cannot be assigned to the string parameter.
The undefined type cannot be assigned to the string type.ts(2345)

I can fix this error with setting an exclemation mark behind the Mongo_url like this:
const conn = await mongoose.connect(process.env.MONGO_URL!);
But then the console tells me:

TypeError: Cannot read property ‘underline’ of undefined

When I log my MONGO_URL it gives me the correct connection path.
Can someone help me out? Thanks

If it is this line:

const conn = await mongoose.connect(process.env.MONGO_URL);

then I think it is saying that process.env.MONGO_URL is possibly undefined. Perhaps:

const conn = await mongoose.connect(process.env.MONGO_URL || '');

or

export const dbConnect = async ()=>{
    try{
        if (!process.env.MONGO_URL) {
          throw new Error('mongo url not defined')
        }
        const conn = await mongoose.connect(process.env.MONGO_URL);
        console.log(`MongoDb connected: ${conn.connection.host}`.cyan.underline);
    }
    catch(error){
        console.log(error)
        process.exit(1);
    }
}

Thanks for your answer kevinSmith. I have tested this and the console throws me no error ‘mongo url not defined’. But the app still crushes with the error:

cannot read property ‘underline’ of undefined

So I think conn.connection.host must be undefined.

Okay, I fixed it by taking out cyan.underline. It seems this library is not working with typescript. Thank you for your solution.

1 Like

Hi KevinSmith, I hope you’re still available to help with this two whole years later :eyes:

the mongoose.connect(process.env.DB_URI) line doesn’t work and it says “No overload matches this call”

Isn’t it telling you that it can be undefined and that isn’t assignable to a string?

Argument of type ‘string | undefined’ is not assignable to parameter of type ‘string’.

I would check it exists before using it.

There isn’t really any useful fall-back value. Falling back on an empty string might satisfy TS, but it doesn’t really help you if the environment variable is undefined. Check the variable exists before using it, you might also want try/catch the connect as well.