简体   繁体   中英

I got error while connecting to mongodb in nodejs

I have folder structure as

.env

    MONGODB_URL = mongodb://localhost/EmployeeDB

.config

    export default {
        MONGODB_URL: process.env.MONGODB_URL
    }

.server.js

import express from 'express'
import mongoose from 'mongoose'
import config from './config'
import dotenv from 'dotenv'
const app = express()
const PORT = 5000

dotenv.config()

const MONGODB_URL = config.MONGODB_URL

mongoose.connect(MONGODB_URL,{
    useCreateIndex: true,
    useNewUrlParser: true,
    useUnifiedTopology: true
}, error=>{
    if(error){
        console.log("Error occurred "+error)
    }else{
        console.log("Database successfully connected")
    }
})

app.listen(PORT,()=>{
    console.log("Server started at port "+PORT)
})

Now it throws error as Error [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.

If I put string directly in.config file as

export default {
        MONGODB_URL: "mongodb://localhost/EmployeeDB"
    }

It works perfectly but, if I use process.env.MONGODB_URL then it throws the error which I have mentioned above. Why it is throwing error when I use process.env.MONGODB_URL ?

I think you have to assign variables in .env without whitespaces around assignment sign =

MONGODB_URL=mongodb://localhost/EmployeeDB

dotenv will load the variables in .env file and assign it to process.env when you call dotenv.config() , which happens after when you imported ./config .

But you can not call dotenv.config() before an import statement, so dotenv provides you an option to use import 'dotenv/config' , so you have to make sure that line comes before import config from './config' , best way is to put it at the top.

import dotenv from 'dotenv/config'
import express from 'express'
import mongoose from 'mongoose'
import config from './config'

const MONGODB_URL = config.MONGODB_URL
/* ... */

You are trying to use the dotenv on the .config file, but the dontenv is not available on it.

A good approach is create a config directory with a index.js file inside of it, there you can share the environment variables and use the dotenv module in your code.

Your code will be something like this:

config/index.js :

require('dotenv').config();

module.exports = {
    MONGODB_URL: process.env.MONGODB_URL,
};

.env :

MONGODB_URL=mongodb://localhost/EmployeeDB

And then you be able to use the env variable anywhere you want simply calling:

server.js :

const config = require('../config');
console.log(`Mongo URL: ${config.MONGODB_URL}`)

In this way your code get a little more organized "IMHO".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM