Search code examples
node.jsmongooseenvironment-variablesdotenv.env

Env Vars is undefined in my seed.js file (NODEJS)


I'm working on this project and everything is working fine, my .env is working and all the env variables is defined in variant files. Then I decided to make a seed file for my database, but it's not able to read the MONGODB_URL value from .env and its output is undefined.
Although it's working from almost anywhere I use it (the same variable!)

I already configured .env in my app.

this is my server.js:

#!/usr/bin/env node
require('dotenv').config()
require('./db/mongoose.js')

const cors = require("cors")
const express = require('express')
const userRouter = require('./routers/user.router')
const answerRouter = require('./routers/answer.router')
const questionRouter = require('./routers/question.router')

console.log(process.env.MONGODB_URL) // works!
const port = process.env.SERVER_PORT // port = 5000

const app = express()
app.use(express.json())
app.use(cors())
app.use(userRouter) 
app.use(questionRouter)
app.use(answerRouter)


app.listen(port,()=>{
    console.log("server is up on port: " + port) //server is up on port 5000
})

this is my .env

SERVER_PORT = 5000
MONGODB_URL='mongodb://127.0.0.1:27017/app0-dev-database'

this is my seed.js

const seeder = require('mongoose-seed');

console.log(process.env.MONGODB_URL) // undefined
seeder.connect(process.env.MONGODB_URL, function(){ // error
    seeder.loadModels([
        './server/models/user.model.js',
        './server/models/question.model.js'
    ]);
    seeder.clearModels (['User','Question' ], function(){
        seeder.populateModels(data, function (err, done){
            if(err) {
                return console.log("seed err", err)
            }
            if (done) {
                return console.log("seed done", done);
            }
            seeder.disconnect()
        })
    })
})

this is my directory structure
the value of MONGODB_URL is undefined
I need to know how to read its value


Solution

  • If seed.js doesn't reqiure/load server.js in any way, you can't rely on the dotenv call there - you need to require it in both files.
    In "seed.js" you should write the following:

    require('dotenv').config()