I am trying to set the test database for the testing purpose, but its not working.
I am trying to connect to mongodb using mongoose, but finding problem in connection er
If we don't want to define the path of the .env file like this,
require('dotenv').config({ path: 'ENV_FILENAME' });
we can place .env file in the same place as our main file, which was App.js in my case. So we could directly write
require('dotenv').config()
In the server directory,
npm install dotenv
In your server.js: If you use "type":"module" in your package.json file then,
import dotenv from 'dotenv';
import mongoose from 'mongoose';
dotenv.config();
or,
const mongoose = require('mongoose')
require('dotenv').config()
Add a .env file in the server directory,
PORT=5000
MONGO_URL= yourURL
In the server.js,
const url = process.env.MONGO_URL
mongoose.connect(url, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => app.listen(PORT, () => console.log("Server up and running!")
.catch((error) => console.log(error.message)
mongoose.set('useFindAndModify', false)
To read from .env file you have to install dotenv ( npm i dotenv / yarn add dotenv) and then just add this on top of your file.
const dotenv = require("dotenv");
dotenv.config();
I think you miss importing env
file.
require('dotenv').config({ path: 'ENV_FILENAME' });
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.
I had same error, for me it was because I was trying to use environment variables in globalSetup
which had the file for initiating db connection.. mongoose.connect(global.__MONGO_URI__
Apparently, environment variables are not initialised yet in globalSetup
so I had to move the code somewhere else, either to setupFilesAfterEnv
or by using Async Test Environment