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