Every time I restart the server with MEN stack, I encounter an error message stating "Cannot read property 'name' of null"

I am currently working on developing a campgrounds application based on Colt Steele's Udemy course "The Web Developer Bootcamp". Everything is going smoothly except for one issue I encountered. When I restart the server and directly access the URL with an ID parameter to navigate to the SHOW ROUTE /campgrounds/:id or any route that requires rendering content from a file, I receive the error message "Cannot read property 'name' of null". It seems like the data is not being properly passed through the callback function when the server restarts. However, if I follow the correct steps by first visiting the index route and then selecting a campground using the interface, everything works as expected. The problem only occurs when entering the URL directly.

    3| 
    4| <h1>This is show.ejs</h1>
 >> 5| <p><%= campground.name %> </p>
    6| <img src="<%= campground.image %> " alt="">
    7| <p><%= campground.description %>  </p>
    8| <br>

Cannot read property 'name' of null
    at eval (/home/roshaan/Desktop/Projects/WebDevBootcamp/YelpCamp/v4/views/campgrounds/show.ejs:13:37)
    at show (/home/roshaan/Desktop/Projects/WebDevBootcamp/YelpCamp/v4/node_modules/ejs/lib/ejs.js:691:17)
    at tryHandleCache (/home/roshaan/Desktop/Projects/WebDevBootcamp/YelpCamp/v4/node_modules/ejs/lib/ejs.js:272:36)
    at View.exports.renderFile [as engine] (/home/roshaan/Desktop/Projects/WebDevBootcamp/YelpCamp/v4/node_modules/ejs/lib/ejs.js:489:10)
    at View.render (/home/roshaan/Desktop/Projects/WebDevBootcamp/YelpCamp/v4/node_modules/express/lib/view.js:135:8)
    at tryRender (/home/roshaan/Desktop/Projects/WebDevBootcamp/YelpCamp/v4/node_modules/express/lib/application.js:640:10)
    at Function.render (/home/roshaan/Desktop/Projects/WebDevBootcamp/YelpCamp/v4/node_modules/express/lib/application.js:592:3)
    at ServerResponse.render (/home/roshaan/Desktop/Projects/WebDevBootcamp/YelpCamp/v4/node_modules/express/lib/response.js:1012:7)
    at Campground.findById.populate.exec (/home/roshaan/Desktop/Projects/WebDevBootcamp/YelpCamp/v4/app.js:70:17)
    at /home/roshaan/Desktop/Projects/WebDevBootcamp/YelpCamp/v4/node_modules/mongoose/lib/model.js:4887:16
    at /home/roshaan/Desktop/Projects/WebDevBootcamp/YelpCamp/v4/node_modules/mongoose/lib/helpers/promiseOrCallback.js:24:16
    at /home/roshaan/Desktop/Projects/WebDevBootcamp/YelpCamp/v4/node_modules/mongoose/lib/model.js:4910:21
    at _hooks.execPost (/home/roshaan/Desktop/Projects/WebDevBootcamp/YelpCamp/v4/node_modules/mongoose/lib/query.js:4390:11)
    at /home/roshaan/Desktop/Projects/WebDevBootcamp/YelpCamp/v4/node_modules/kareem/index.js:135:16
    at _combinedTickCallback (internal/process/next_tick.js:131:7)
    at process._tickCallback (internal/process/next_tick.js:180:9)

The main app.js file has the following code:

var express = require("express"),
    app = express(),
    bodyParser = require("body-parser"),
    mongoose = require("mongoose"),
    Campground = require("./models/campground"),
    seedDB = require("./seeds");
    
    
mongoose.set('useNewUrlParser', true);
mongoose.set('useFindAndModify', true);
mongoose.set('useCreateIndex', true);
mongoose.set('useUnifiedTopology', true);
mongoose.connect('mongodb://localhost/yelp_camp');

app.use(bodyParser.urlencoded(
    { extended:true }
    ));
app.set("view engine", "ejs")

seedDB();
        

app.get("/", (req, res) => {
    res.render("landing");
})

// INDEX - display all campgrounds
app.get("/campgrounds", (req,res)=>{
    // Retrieve all campgrounds from the database
    Campground.find({},(err,campgrounds)=>{
        if(err){
            console.log(err);
        }else{
            res.render("campgrounds/index", {campgrounds:campgrounds});
        }
    });
});

// CREATE - Add new campground to DB
app.post("/campgrounds", (req,res) => {
    var name = req.body.name;
    var image = req.body.image;
    var desc = req.body.description;
    var newCampground = {name: name, image:image, description:desc}
    // Create a new campground and save it to the DB
    Campground.create(newCampground, (err, newlyCreated)=>{
        if(err){
            console.log(err);
        } else{
            // Redirect back to the campgrounds page
            res.redirect("/campgrounds")
        }
    });
});

// NEW - display form to create a new campground
app.get("/campgrounds/new", (req,res) => {
    res.render("new");
});

// SHOW - display information about one campground
app.get("/campgrounds/:id",(req,res)=>{
    // Find the campground with the provided ID
    Campground.findById(req.params.id).populate("comments").exec((err, campground)=>{
        if(err){
            console.log(err);
        }else{
            // console.log(foundCampground);
            // Render the show template with that campground
            res.render("campgrounds/show", {campground: campground});
        }
    });
});

// ===================
// COMMENTS ROUTES
// ===================

app.get("/campgrounds/:id/comments/new", (req, res)=> {
    // Find the campground by its ID
    Campground.findById(req.params.id, (err, foundCampground)=>{
        if (err) {
            console.log(err);
        } else {
            
            res.render("comments/new", {campground:foundCampground})
        }
    });
});

const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
    console.log(`the YelpCamp Server has started on port: ${PORT} `);
});

Answer №1

After doing some investigating, I realized the root of the problem. It seems that the seedDB() function is altering the Object Ids, causing issues with using the same Id

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

Express.js restricts the number of requests to a maximum of 6

I am facing an issue with my Flask server that streams image data using the multipart/x-mixed-replace header. The Express server is set up to connect to the Flask server, receive the image data, and then deliver it to the client also utilizing the multipar ...

Setting the CSS position to fixed for a dynamically generated canvas using JavaScript

My goal is to fix the position style of the canvas using JavaScript in order to eliminate scroll bars. Interestingly, I can easily change the style using Chrome Inspector with no issues, but when it comes to implementing it through JS, I face difficulties. ...

Having issues with Vue.js when using Vue-strap Radio Buttons

While developing my web application with vue.js, I encountered an issue with radio buttons when I switched to using bootstrap style. I understand that I need to use vue-strap for proper data binding with bootstrap styled radio buttons in vue.js, but I am s ...

Validation in PHP and Javascript is only partially effective

I encountered an issue with my form validation setup that utilizes JavaScript, Ajax, and PHP. While the errors are correctly displayed when the form is filled incorrectly, I am unable to submit the form even if there are no errors. Clicking the submit butt ...

Conceal div elements and retain their status when the page is reloaded or switched

I currently have 3 div elements displayed on a webpage: header-div fixed_menu_div page_cont Each of these divs are styled with the following CSS properties: #header-div { top:0; left:0; display:inline; float:left; } #page_cont { mar ...

Instructions for implementing tooltips on a pie chart slice when hovering with the mouse pointer, using the canvas

var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); var cw = canvas.width; var ch = canvas.height; ctx.lineWidth = 2; ctx.font = '14px verdana'; var PI2 = Math.PI * 2; var myColor = ["Gr ...

NodeJS file execution through a stored procedure

Everything I've come across regarding the topic revolves around using a NodeJS program to call a stored procedure. Inquiring: Is it feasible to reverse this process? Can a stored procedure be designed to call/execute a NodeJS file/program instead? I& ...

Can you explain the execution process of this Http.post method and provide details about the code path it follows

As I delve into the world of web development, one aspect that has me stumped is the functionality of the Http.post section within a project I stumbled upon on GitHub. Specifically, this pertains to an ExpressJS with Typescript repository I came across. So, ...

Node.js: Organizing multiple routes in a single router file

Is it possible to have multiple routes defined in a single router file? For example, let's say we have Company and User tabs and I want to have 1 router file for each tab. All company-related calls should be handled by the Company router and user-rela ...

Combining Watson Assistant (formerly known as Conversation) with Telegram and Facebook

I'm feeling a bit lost when it comes to connecting my Watson bot with messaging platforms like Facebook Messenger. I created the bot using the Watson Conversation service and deployed it on a Bluemix Cloud Foundry node.js app. While it's working ...

iOS app launch does not trigger Phonegap handleOpenURL

Receiving an alert message when the app is open in the background. However, when I close the app from the background and then relaunch it, the alert message doesn't appear. The handleOpenURL function cannot be invoked in JavaScript when the app is lau ...

Guide on importing table information into an array using jQuery

I am facing an issue where I want to extract values from a dynamically generated table and then send those values in an AJAX call. The problem is that even though I am able to increase the number of rows in the table dynamically, when I try to capture the ...

Incorporate data into the input value rather than the div using Ajax technology

This ajax function is working perfectly, but I would like to modify the location where the result should appear. <script type="text/javascript"> function submitForm1() { var form1 = document.myform1; var dataString1 = $(form1).serialize(); $.ajax ...

Troubleshooting issues with rowspan in a Datatable

I am currently utilizing jQuery DataTables to display my grid data and implementing the rowspan concept with the rowsGroup option. Initially, it works well by spanning some rows and looking visually pleasing, but eventually, it starts failing. Here are so ...

Moving from traditional web pages to a mobile application using NextJS has brought about the error "rest.status is

Currently, I am in the process of upgrading from Next 13.2.5 to version 14.1.0 and switching to using app/api/example/route.js instead of pages/api/example.js. After making these changes, I encountered an error stating TypeError: res.status is not a funct ...

JavaScript: retrieving undefined value from a text element

My goal is to retrieve the text entered into each textbox by querying and looping through their ID tags. However, when I attempt to print what I have retrieved, it always displays "undefined". Seems like your post consists mostly of code: </h ...

What is the best approach for managing CNAME records during domain resolution?

When my web application receives an unfiltered string from an untrusted user, it must determine whether this string, when used as a hostname, resolves to an IPv4 or IPv6 address within a forbidden range specified by predefined rules. If the string appears ...

Guide to creating a unique React component for displaying a single popup upon clicking with the ability to pass props to it

As someone who is still learning React, I decided to challenge myself by creating a Jeopardy game using this framework. My current idea is to have a popup appear when a player clicks on a box on the Jeopardy board, displaying the clue associated with that ...

Retrieving information from the database and transferring it to the front end via the router

I have been working on a MERN Expo app login and sign-in page. However, I am facing an issue with fetching data from the backend after clicking the sign-in button. Even though I have implemented the find query in the Express router, I am unable to retrieve ...

Move your cursor over the image to activate the effect, then hover over it again to make the effect disappear

Looking to enhance my images with hover effects. Currently, all the images are in grayscale and I'd like to change that so that when you hover over an image, it reverts to full color and remains that way until hovered over again. I've noticed so ...