futureLinker
futureLinker

Reputation: 25

MongoDB connection error nodejs express mongoose

I'm a beginner and trying to test some basic connection to MongoDB with node and express and mongoose and cannot find why is returned as "undefined".

I'm using a dotenv module to use an env variable, any advice?

MongooseError: The uri parameter to openUri() must be a string, got "undefined". Make sure the first parameter to mongoose.connect() or mongoose.createConnection() is a string.

This is my code:

index.js:

import app from './app'
import './database'

app.listen(app.get('port'))
console.log('Greetings from express')

database.js:

import mongoose from "mongoose";
import config from './config'

(async () => {
    const db = await mongoose.connect(config.mongodbURL, {
        useNewUrlParser: true,
        useUnifiedTopology: true,
    });
    console.log('Database connected to:', db.connection.name);
})();

config.js:

import { config } from "dotenv";
config();

export default {
    mongodbURL: process.env.MONGODB_URI,
};

.env:

MONGODB_URI = mongodb://localhost/tasksapi

Upvotes: 0

Views: 1014

Answers (2)

Kandonga
Kandonga

Reputation: 71

Yes what you are doing here

await mongoose.connect(config.mongodbURL,

change it to await mongoose.connect(process.env.mongodbURL,

and store the mongodb url in you config.env file like so

mongodbURL=mongodb+srv://USERNAME:<PASSWORD>@cluster<CLUST>/<DBNAME?retryWrites=true&w=majority

, that will work for you

Upvotes: 0

A McBride
A McBride

Reputation: 405

If you aren't amending your config files, then you may not have to have your config.js file, you could simply call config() in index.js, and any files loaded after it will have access to process.env.

In that case, your code would look as follows:

// index.js

import {config} from 'dotenv'
config()

import app from './app'
import './database'

app.listen(app.get('port'))
console.log('Greetings from express')
// database.js

import mongoose from "mongoose";
import config from './config'

(async () => {
    const db = await mongoose.connect(process.env.MONGODB_URI, {
        useNewUrlParser: true,
        useUnifiedTopology: true,
    });
    console.log('Database connected to:', db.connection.name);
})();

Alternatively, if you wish to keep your config.js, then calling dotenv's config() in index.js would also ensure that your envvars are loaded by the time the config.js exports them.

Upvotes: 0

Related Questions