I keep encountering an error in my server.js. Can someone assist me with how to resolve this?
The Error:
MongooseError: The `uri` parameter to `openUri()` must be a string, but it is "undefined". Ensure that the first parameter passed to `mongoose.connect()`
or `mongoose.createConnection()` is a string.
at NativeConnection.Connection.openUri (C:\Users\Priyansh\Desktop\WorkOut\backend\node_modules\mongoose\lib\connection.js:694:11)
at C:\Users\Priyansh\Desktop\WorkOut\backend\node_modules\mongoose\lib\index.js:380:10
at C:\Users\Priyansh\Desktop\WorkOut\backend\node_modules\mongoose\lib\helpers\promiseOrCallback.js:41:5
at new Promise (<anonymous>)
at promiseOrCallback (C:\Users\Priyansh\Desktop\WorkOut\backend\node_modules\mongoose\lib\helpers\promiseOrCallback.js:40:10)
at Mongoose._promiseOrCallback (C:\Users\Priyansh\Desktop\WorkOut\backend\node_modules\mongoose\lib\index.js:1225:10)
at Mongoose.connect (C:\Users\Priyansh\Desktop\WorkOut\backend\node_modules\mongoose\lib\index.js:379:20)
at Object.<anonymous> (C:\Users\Priyansh\Desktop\WorkOut\backend\server.js:10:10)
at Module._compile (node:internal/modules/cjs/loader:1105:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
server.js file
require('dotenv').config()
const express = require('express')
const WorkoutRoutes = require('./routes/workouts.js')
const mongoose = require('mongoose')
const app = express()
app.use(express.json())
app.use('/api/workouts', WorkoutRoutes)
mongoose.connect(process.env.MONGO_URI)
.then(() => {
console.log('connected to database')
// listen to port
app.listen(4000, () => {
console.log('listening for requests on port', 4000)
})
})
.catch((err) => {
console.log(err)
})
.env file
MONGO_URI=mongodb+srv://Priyansh:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5707253e2e3639243f666564172038253c382223793e3a2533363a3f793a38393038333579393223">[email protected]</a>/?retryWrites=true&w=majority
workouts.js file
const express = require('express')
const router = express.Router()
router.get('/',(req,res) =>{
res.json({msg :"Getting a workout"})
})
router.post('/',(req,res) =>{
res.json({msg :"Posting a workout"})
})
router.get('/:id',(req,res) =>{
res.json({msg :"Getting a single workout"})
})
router.delete('/:id',(req,res) =>{
res.json({msg :"Deleting a workout"})
})
router.patch('/:id',(req,res) =>{
res.json({msg :"Updating a workout"})
})
module.exports = router