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
i have encountered the same error, this thread didn't help... here's my solution it was simple! im using express, mongo, mongoose, and dotENV
file 1 === db.js
import mongoose from 'mongoose';
const connectDB = async ()=>{
try{
const conn = await mongoose.connect(process.env.MONGO_URI,{
//must add in order to not get any error masseges:
useUnifiedTopology:true,
useNewUrlParser: true,
useCreateIndex: true
})
console.log(`mongo database is connected!!! ${conn.connection.host} `)
}catch(error){
console.error(`Error: ${error} `)
process.exit(1) //passing 1 - will exit the proccess with error
}
}
export default connectDB
file 2= server.js
import express from 'express'
import dotenv from 'dotenv'
import connectDB from './config/db.js' // DB connection
import products from './data/products.js'
dotenv.config()
const PORT = process.env.PORT || 5000
const mode = process.env.NODE_ENV
const app = express()
connectDB() //this function connects us to the DB!!!
. . . more code…
> solution: the connectDB() expression must come after the dotenv.config() expression. and that's it ! :)