Articles related to Express.js - encountering issues when attempting to read properties from a null object

I'm trying to display related articles based on categories using Mongoose for querying data from MongoDB.

However, when I attempt the code below, I encounter an error message stating "TypeError: Cannot read properties of null (reading 'category')". Interestingly, the console.log shows an array with categories first before throwing the error "cannot read"..

As a beginner in express js, I would appreciate any hints or tips from experienced users.

 exports.articleDetail = async (req, res) => {
        const article = await Article.findOne({ slug: req.params.slug }).populate('category').populate('author');
        const articlecategories = article.category
        categories = []
        for(let i=0;i<articlecategories.length;i++){
          const category = articlecategories[i]
    
          categories.push(category._id)
        }
        console.log(categories)
        const relatedarticles = await Article.find({ category : { $all : categories }})
        console.log(article);
        res.render('article', { article, relatedarticles })
    }

Edit

Thank You all for answers. I have a solution. Problem is that when loop through article categories, I get no category ID but new ObjectId: new ObjectId("636bc1c64f7470f2557b61d7")

To let this work, I must use .toString() and get only Id and then push this Id to array.

This is working code:

 exports.articleDetail = async (req, res) => {
    const article = await Article.findOne({ slug: req.params.slug }).populate('category').populate('author');

    categories = []
    for(let i=0;i<article.category.length;i++){
      const category = article.category[i]

      const catid = category._id.toString()
  
      categories.push(catid)
    }

    console.log(categories)

    const articles = await Article.find({category: { $all: categories }}).populate('author')

    res.render('article', { article, articles })
}

Answer №1

It is possible that the await Article.findOne call is returning null because the object was not found.

To handle this situation, you can check if anything is returned and if not, return an error message like so:

exports.articleDetail = async (req, res) => {
        const article = await Article.findOne({ slug: req.params.slug }).populate('category').populate('author');
        if (!article) return res.status(404).json(/* insert your error response here */);
        const articleCategories = article.category;
        categories = [];
        for(let i=0;i<articlecategories.length;i++){
          const category = articleCategories[i];
    
          categories.push(category._id);
        }
        console.log(categories);
        const relatedArticles = await Article.find({ category : { $all : categories }});
        console.log(article);
        res.render('article', { article, relatedArticles });
    }

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

How can I connect the box using the Interactive Picture jQuery tool?

When using the Interactive picture jQuery, I have the following code snippet within my document: jQuery(document).ready(function(){ $( "#iPicture6" ).iPicture({ animation: true, animationBg: "bgblack", animationType: "ltr-slide ...

HTML elements not displaying in Ajax form

I am encountering an issue with my ajax based feedback form where the form is displaying the html from the response instead of processing it correctly. Here is the JQuery code: $(document).ready(function() { var form_holder = $('#form-holder'); ...

The VueJS component from a third-party source is not located in the node_modules directory

Utilizing vue-cli version 3 for a fresh vuejs project (I've been dedicating ample time to learning vuejs, but this marks my initial attempt at integrating a third-party component). I'm aiming to incorporate a visually appealing grid component. Th ...

What do the letters enclosed in brackets signify?

I am currently working with a library known as Monet.js, and within the documentation, there are descriptions that look like this: Maybe[A].map(fn: A => B) : Maybe[B] I am unsure of what the letters inside the brackets stand for. Is there anyone who c ...

Storing JWT securely in cookie or local storage for a Node.js/Angular 2 web application

I've been researching how to save jwt tokens in either local storage or cookies but I'm having trouble finding clear instructions online. Can someone provide guidance on how to instruct the server to recognize a user for future sessions? //a ...

ER_CON_COUNT_ERROR: The maximum number of connections between knex and bookshelf has been exceeded

I have developed a basic rest api using express, knex, and bookshelf. During my performance testing with Jmeter, I observed that calling the API to execute the following query does not pose any issues: public static async fetchById(id: number): Promise&l ...

Is it possible to detect inline elements that have been wrapped?

I am facing a challenge with displaying an indefinite amount of in-line elements. Depending on the width of the browser, some elements may shift to a new line. I am curious to know if it is possible to identify and isolate these rows of elements, or if the ...

Guide: Extracting a targeted input field value from an external webpage with Javascript

After successfully retrieving the webpage content from an external website using ajax, my next goal is to develop a function that can extract a specific input field value which is already pre-filled. The structure of the webpage content looks something li ...

Query MySQL and automatically populate form fields with the data retrieved after the user triggers an "onexit" or "onsubmit" event, all without having to reload the page,

Seeking a way to auto-fill form fields with data from MySQL database. The goal is to input a value in a text field, search the database matching that value, and populate the remaining form fields without having to navigate away from the page. If anyone h ...

Organize arrays within arrays in Javascript

My array of data is structured for visualization as shown below: var Dataset1 = [ { "commentBy": "saurabh", "comment": "Testing", "datestamp": "07/07/2017", "weekcount": 1 }, { "commentBy": "raman", "comment": "Planning", ...

Exploring innovative methods for integrating dialog boxes in Chrome extensions?

Currently working on a Google Chrome extension and inquiring about the various choices for incorporating dialog boxes. I am looking for a solution that includes distinct head and body elements. The plan is to design custom-styled forms with jQuery. Are t ...

Learn how to utilize Javascript to easily drag and drop an image within the same block

I am encountering an issue with dragging and dropping images or swapping them using JavaScript. I have tried to implement this in the code below, where clicking on icons moves them onto a colored div. However, I am now trying to drag and drop the images wi ...

Angular JS appears to be causing the DOM to freeze up while utilizing the ng-repeat directive to loop through

I have a current app where clicking a button triggers an $http request to fetch and return some data. The retrieved information is then used to update the $scope variables rows and columns, which are then looped through using ng-repeat. However, I've ...

Tips for recognizing hyperlinks within a block of text and converting them to clickable links in Angular 2

My task is to create clickable links within a paragraph of strings. I tried using a custom pipe, but seem to be missing something essential. Here's my attempt: import { Pipe, PipeTransform } from '@angular/core'; import { DecimalPipe ...

Sending numerous arguments to getStaticPaths() in nextjs

I am looking to create two different routes: /midterm/cs611 /finalterm/cs611 My goal is to display distinct content when accessing the /midterm/cs611 endpoint, and different content when accessing the /finalterm/cs611 endpoint. However, I am running into ...

Update ng-Bootstrap ToDate field by removing the date when selecting a fromDate

Is there a way to clear the date from the toDate input field while selecting a date from the fromDate input field in ng-bootstrap? <form class="row row-cols-sm-auto" *ngIf="showDateRangeImp"> <div class="col-12" ...

Utilizing properties from the same object based on certain conditions

Here's a perplexing query that's been on my mind lately. I have this object with all the styles I need to apply to an element in my React app. const LinkStyle = { textDecoration : 'none', color : 'rgba(58, 62, 65, 1)', ...

Showcase an Array on an HTML page using EJS

When a user posts an object on my website forum using Ejs/NodeJs/MongoDb, it creates a new object with properties like title, comment, and reply array. I have successfully displayed the titles and comments in different HTML elements, but I am facing an i ...

Securing an Express.js server against brute force attacks

I'm currently developing an API using Node.js and Express, with my application being hosted on the Openshift free plan. I am looking for a way to secure my routes from potential brute force attacks. Ideally, I would like to implement a mechanism that ...

React Native automatically triggers the onPress event when using withNavigation

It seems that onPress should only be triggered by a touch event. Initially, this was the case, but when using withNavigation in a screen outside of the StackNavigator, onPress appears to render automatically. HomeScreen.js function mapStateToProps(state) ...