Error message being displayed multiple times due to a mongoose string issue

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

Answer №1

Can you display the environment variable to understand how the program accesses it? If the type is undefined, it could mean that the program is unable to locate it or is interpreting it in a specific manner (this is just my debugging approach as I'm still learning with no experience).

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Verify if the input field is empty or not for a dynamic text field in AngularJS

Can someone help me with validating multiple text fields in an angularjs controller function? I am currently working with angular js version 1.5.6. Here is the HTML code: <div ng-controller="Controller"> <div ng-repeat="data in datas trac ...

Having issues with Bootstrap flip div not functioning properly when clicked on a mobile device?

I am currently working on a website and encountering an issue. Here is the code snippet I am using: https://jsfiddle.net/3caq0L8u/ The objective is to flip a div when a button is clicked. The button responsible for flipping the div resides in both the " ...

causing a `Json::LogicError` to be thrown

When trying to create a JSON object utilizing jsoncpp and encountering an error when adding it to an array, the code snippet is causing issues: Json::Value zone1; Json::Value coord; zone1["zoneID"] = "shop1"; zone1["stamp"] = ...

Optimal method in Ruby on Rails for sending model-specific attributes for grouping functions

I am currently working on implementing client-side list grouping functionality in my Rails application. The goal is to create a user list view where the user model can be grouped by different attributes such as email, name, title, etc. My plan is to have t ...

Displaying a JSON array in C++ using the nlohmann library

I utilized the nlohmann library to create JSON objects with the following code snippet: nlohmann::json dataJson; auto data = dataJson.array(); data[0]["message"] = "String"; data[0]["timestamp"] = 123; The current output is {"message":"String", "timest ...

Utilizing Next.js with formidable for efficient parsing of multipart/form-data

I've been working on developing a next.js application that is supposed to handle multipart/form-data and then process it to extract the name, address, and file data from an endpoint. Although I attempted to use Formidable library for parsing the form ...

"Dynamic Axis Scaling in Bokeh: A Versatile Feature

I have a situation similar to the one discussed in this question on Stack Overflow, but with additional code examples. In my Django app, I've built a Bokeh chart that visualizes the times swam in competitive swimming events over time. The chart utiliz ...

Addressing the Issue in MongoDB Entity Framework Core: Unwritable Expression Required

I am currently using Entity Framework Core alongside MongoDB, but I am encountering an issue when attempting to utilize the FirstOrDefault method. The base class I have is called SignInCredentials: public class SignInCredentials(string username, string? p ...

Ways to verify various keys using JsonPath

I am attempting to locate a specific object within a JSON array by utilizing JsonPath. Below is the JSON data I am working with: [ { "bpm": "766", "time": "20:14:57", "confidence": "0" }, { "bpm": "766", ...

Tips for maintaining a user's logged-in status when the "remember me" option is selected

I need to implement a feature that keeps a user logged in even if they refresh or close the browser. This is the code I have written: index.php <?php include_once('elogFiles/view/myIncludes.php'); ?> <div class="container" ...

Extracting data from an array using Angular

Currently, I am developing an Angular application that involves handling an array structured like the one below. [ { Code: "123", Details:[ { Id: "1", Name: "Gary" }, { ...

Using the append method to call an Angular directive

Attempting to invoke an angular directive with HTML text being appended in a controller: var loadReviews = function(){ var theDiv = $("#rlist") for(var i=0; i<vm.reviewlistByUpvote.length; i++){ var review = vm.reviewlistByUpvote[i]; v ...

serialize the object to JSON format and store it in SharedPreferences

Is my approach correct? I'm trying to save the cards array (object) using SharedPreferences when the back button is pressed, but I keep encountering an error whenever I run the program. Should I convert the object at onCreate instead? @Override p ...

Require Assistance With Creating a Typing Animation in JavaScript?

Recently, I created a JavaScript text typer code: Here is the CSS: body { background-color: black; } #writer { font-family: Courier; font-size: 12px; color: #24FF00; background-color: black; } And here is the JavaScript: var text ...

Transferring data and parameters between the Client-Side and Server-Side

I am currently working on setting up an express.js server, but I am struggling to figure out how to send and receive data effectively. Specifically, I have an input field where users can enter their email addresses. I want this email address to be sent to ...

Support with Elastic Stack: Enhancing Logstash with geoip functionality

I've been grappling with this problem for some time now, trying to decipher the syntax required to utilize the logstash filter. Within my program, I am logging the user's IP address and other values in key-value pairs within a JSON format. The s ...

What is the best way to access a value within a JSON object in a React render method?

Overview I am currently working on creating a blog using React and JSON data. Upon checking this.state.blogs, I am getting the output of: [object Object],[object Object],[object Object]. I have attempted to use the .map function but I am not sure how to ...

Ways to address duplicate data within a specific collection in MongoDB

https://i.sstatic.net/RLCXY.jpg Here is my current challenge: I have a problem set represented in the form of an image. The task at hand involves analyzing the data presented which consists of 5 columns. Each alphabet in the first 4 columns has a weighted ...

Triggering JSON command to launch a new tab

Having encountered a peculiar issue, I've been combing the internet for answers with little luck. My challenge lies in parsing a JSON object successfully, but when linking to my HTML file, a new tab opens after clicking submit on the form. Despite fee ...

Executing test spec before promise resolution in $rootScope.$apply() is completed

When writing angular unit tests using Jasmine with angular-mocks' httpBackend, I successfully mocked my backend. However, one of my tests is encountering issues with an http call where a value is set to scope after the request is complete (in then()). ...