Struggling to add an object to my Topic array using push

I'm in the process of developing a forum platform. Below is my Topic schema:

const topicSchema = new mongoose.Schema({
  author: {
    type: String,
    ref: "User", // Reference to the user who created the Topic
    required: true,
  },
  title: { type: String, required: true },
  content: {
    type: String,
    required: true,
  },
  posts: { type: Array, ref: "Posts" }, // array of posts
  postCount: { type: Number, default: 1, required: true },
  createdAt: {
    type: Date,
    default: Date.now,
  },
});

This code snippet utilizes the above schema and a form filled out by the user to store data into the database.

const topic = new Topic({
      title: req.body.title,
      content: content,
      author: req.body.author,
    });

A similar approach is taken for managing message responses with a Posts schema which saves messages and their authors.

router.post("/:topicId"

const { topicId } = req.params;

const topic = Topic.findById(topicId);

const post = new Post({
  author: req.body.author,
  message: message,
});
console.log(post);
console.log(topic.title);

topic.posts.push(post);

// Save new post if form data is valid.
post
 .save()
 .then(function (post) {
   res.redirect("/");
   })
 .catch(function (err) {
   console.log(err);
   });

Overall, my code is functioning well without errors. However, I am facing an issue with using push in the post section resulting in the following error:

Cannot read properties of undefined (reading 'push')
. The goal is to append a user's post under a specific topic so that all responses can be displayed on the page. Despite several attempts, this action triggers the mentioned undefined error.

Answer №1

Executing a mongoose query can be done in two ways.

  • If you provide a callback function, Mongoose will execute the query asynchronously and pass the results to the callback.
  • A query also supports a .then() function, making it usable as a promise.

When using Topic.findById, ensure that you treat it as an asynchronous call. If you try to push a new item to the posts array without awaiting the result of Model.findById, you will encounter a

"Cannot read properties of undefined"
error. Here's how you can handle it:

const { topicId } = req.params;

// Use async/await to fetch the topic from the database
const topic = await Topic.findById(topicId);

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

"Changing background color, incorporating hover effects, utilizing !important, and manipulating .css properties with

Encountered a dilemma. I devised a "tabs" feature illustrated in the following demo: http://jsfiddle.net/4FLCe/ The original intention was for the tab to change color to A when hovered over, and to color B when clicked on. However, as shown in the demo, ...

Using a function as a parameter in a React component constructor

I have a question about a snake game I'm developing using React. After reading a post on Stack Overflow discussing setting functions inside the constructor, I am facing an issue with calling a function (foodGenerator) from within another function (sn ...

Is it possible to prevent the selected option from being available in other select lists using AngularJS?

Can anyone help me figure out how to disable an option in one select list when it is selected in another using AngularJS? I have set up a select list for From Year and To Year with ng-repeat, which is working fine. Now, I just need to implement the functio ...

JSON with a null character

Despite spending an hour searching online, I feel a bit hesitant to ask this question. Can null characters (ascii null or \0) be used within JSON? I know they are not allowed within JSON strings, but my query is whether they can be included in the bod ...

issue concerning slide functionality and ajax integration

I'm facing an issue with the structure of my HTML. Here is the setup I have: <div id ="slide1"> <form method="post" id="customForm" action=""> //my content - name, email, mypassword, pass2 </for ...

Retrieving data from an external API using Express.js and displaying it on a website

I'm facing a challenge in handling a solution with node.js and express.js utilizing pug for rendering HTML. I need to render on a single page by retrieving values from separate HTTP GET requests from different websites. My goal is for express/node to ...

Components of an Irregular Array

Are the elements of a Jagged Array in c# classified as 'Value type' or 'Reference type'? My understanding is that since Jagged arrays are arrays of arrays, they should be categorized as reference types rather than value types. This is b ...

Altering the input field's content in response to a button click through JavaScript's addEventListener function

I am struggling to get the input text from a form field to change when a button is clicked using JavaScript. I can't seem to figure out why it isn't working correctly. Any assistance would be greatly appreciated. <!doctype html> & ...

Executing various angular 4 applications simultaneously using a shared Node.js server for rendering purposes

What is the best way to configure index files for both front-end (Angular 4 CLI) and backend (Angular 4 CLI) in order to manage two separate Angular apps? ...

Using an external JavaScript script may encounter difficulties when loading pages with jQuery

Trying to utilize jQuery for loading html posts into the main html page and enabling external scripts to function on them. Utilizing a script (load.js) to load posts into the index.html page: $(document).ready(function () { $('#header').loa ...

Error: Unable to modify a property that is marked as read-only on object '#<Object>' in Redux Toolkit slice for Firebase Storage in React Native

Hey there! I've been working on setting my downloadUrl after uploading to firebase storage using Redux Toolkit, but I'm facing some challenges. While I have a workaround, I'd prefer to do it the right way. Unfortunately, I can't seem to ...

Strategies for refining document types in mongoDB

Attempting to filter by type in mongoDB for "vod", "playlist", "series" This is how I'm trying: let filter = { type: "vod" && "playlist" && "series" } let video = await Video.find(filter); Unfortunately, it's not functioning as expected. ...

displaying li tag depending on the index value within angularjs

I have an HTML structure similar to the following: <div class="main"> <ul> <li ng-repeat='save in saves'> <h3>{{save.name}}</h3> <div > <ul> ...

Is there a way to adjust the image opacity of a background using Material UI?

Is there a way to adjust the opacity of a background image using Material UI? I attempted to achieve this by utilizing the makeStyles hook in Material UI. Here is an example of my code: import React from 'react'; import {Box,Typography } from &ap ...

Having issues with $emitting not working for parent-child components in Vue. Any ideas on what I might be doing incorrectly?

I have a login component that I need to call in the main vue component of App.vue. Within the login vue, when I click on any button, it should activate another vue component using Vue.js router to replace the login page. I have searched for solutions but h ...

What is the best way to combine two arrays of objects in AngularJS?

How can I merge the existing object array with another one in AngularJS to implement the "load more" feature? Specifically, I want to add the AJAX response to the existing data each time. Currently, I have a variable called $scope.actions that holds the ...

Activating two buttons in jquery will trigger this action

I am currently working on developing a filter button that will perform different actions based on which buttons are pressed. Pressing button1 will trigger one action, while pressing button2 will trigger another action. If button1 is pressed first, followe ...

Is there a way to trigger a modal popup when hovering over a Bootstrap 5 card?

After coming across a handy template online, I decided to implement a modal pop-up feature when hovering over cards using Bootstrap 5. Here's what I have so far: class SavedEpisodes extends Component { $(function() { $('[data-toggle=&qu ...

Transitioning from curl to jQuery's $.ajax() method

Recently, I encountered a challenge while trying to switch the curl code used for an API known as TextRazor to jquery's AJAX due to certain limitations on the platform. Despite exploring various solutions suggested by the community in response to simi ...

Tips for creating a div that gracefully fades out its background image when hovered over, while keeping the internal content unaffected

I am looking to create a hover effect on a div element that has a background-color, background-image, and text. What I want is for the background-image to slowly disappear when the div is hovered over, while keeping the text and background color visible. I ...