What is the best way to show the user profile on a Forum?

I am struggling to figure out how to display the username of a user on my forum page. I currently only have access to the user's ID and need help in extracting their name instead.

It seems that I lack knowledge about mongoose and could really benefit from someone who is familiar with it.

My Forum Model:

Within my forum model, I am grabbing the ObjectId("") from the User as shown below:

const forumSchema = ({
   forumName: {
      type: String,
      required: true,
   },
   forumDescription: {
      type: String,
      required: true,
   },
   user: { 
      type: Schema.Types.ObjectId,
      ref: 'user'
   },
   published_on: {
      type: String,
      default: moment().format("LLL")
   },
});

my userModel:

const UserSchema = mongoose.Schema({
   userID: {
      type: String,
      required: true,
   },
   userName: {
      type: String,
      required: true,
   },
   password: {
      type: String,
      required: true,
   },
   isAdministrator: {
      type: Boolean,
      default: false,
  },

});

Front-end :

Currently, I can only see the user's id in {forum.user}, but what I actually want is their name.

 <footer className="blockquote-footer">
    Created by:{forum.user}
    Created on:{forum.published_on.substring(0,300)}
 </footer>

What I retrieved in MongoDB Compass:

_id:ObjectId(61e052686147a6f0bd1e65df)
forumName:test33
forumDescription:"test."
published_on:"January 13, 2022 5:25 PM"
user:ObjectId(61dd83db2b8b9b6e2a8e7f0b)
__v:0

What I obtained in Postman:

{
  "_id": "61e054809b71d933dbefae22",
  "forumName": "testtest",
  "forumDescription": "testing.",
  "published_on": "January 13, 2022 5:27 PM",
  "user": {
    "_id": "61dd83db2b8b9b6e2a8e7f0b",
    "userID": "admin",
    "userName": "admin",
    "password": "$2b$10$qwAZspGbchBkZ6eoe8ODxOiLeOrK2J3cltrLMKlVB/6TRhL5e1qAy",
    "isAdministrator": true,
    "__v": 0
  },
  "__v": 0
}

Forum Action list:

export const createNoteAction =
  (forumName, forumDescription) => async (dispatch, getState) => {
    try {
      dispatch({
        type: NOTES_CREATE_REQUEST,
      });

      const {
        userLogin: { userInfo },
      } = getState();

      const config = {
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${userInfo.token.token}`,
        },
      };
      const url = "http://localhost:8080/forum/";

      const { data } = await axios.post(
        url,
        { forumName, forumDescription },
        config
      );

      dispatch({
        type: NOTES_CREATE_SUCCESS,
        payload: data,
      });
    } catch (error) {
      const message =
        error.response && error.response.data.message
          ? error.response.data.message
          : error.message;
      dispatch({
        type: NOTES_CREATE_FAIL,
        payload: message,
      });
    }
  };

My Frontend page:

{forum &&
        forum.map((forum) => (
          <Accordion defaultActiveKey="0">
            <Accordion.Item style={{ margin: 10 }} key={forum._id}>
              <Accordion.Header style={{ display: "flex" }}>
              <span
                  style={{
                    color: "black",
                    textDecoration: "none",
                    flex: 1,
                    cursor: "pointer",
                    alignSelf: "center",
                    fontSize: 18,
                  }}
                >
                      {forum.forumName}
                </span>
                </Accordion.Header>
                <Accordion.Body>
                <blockquote className="blockquote mb-0">
                  <ReactMarkdown>{forum.forumDescription}</ReactMarkdown>
                  <footer className="blockquote-footer">     
                  Created by:{forum.user.userName}                      
                        Created on: {forum.published_on.substring(0,300)}               
                      </footer>

Answer №1

If you want to include users within forums, you can use the populate method like this example:

Forum.find().populate("user")

After executing this code, you will have access to complete user objects instead of just their _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

Show the button's value inside a div when clicked using Javascript and HTML

I am troubleshooting an issue where the value of a button is not displayed in the picked_letters div when the button is clicked, despite having the appropriate code in both the html and javascript files. The structure of the html file is as follows: < ...

"Utilize JavaScript to detect both the loading and unloading events on a webpage

I attempted to capture the window.open onload and onunload events. The issue arises when I use URLs from other domains. For example: When the URL is for the same page, both events trigger as desired. window.open("/") View PLUNKER with same page URL .. ...

After utilizing a while loop with class objects, make sure to reset them afterwards

I am facing a dilemma due to Js referencing objects. Within my Js "class," I have created a new player with various variables, strings, arrays, and functions to check specific conditions related to those variables. As part of my code, I am running a whil ...

Can different versions of Node be used simultaneously for various Node scripts?

Currently, I am utilizing nvm. Can a specific node version be used for a particular script? For instance... Using node 6 forever start -a -l $MYPATH/forever.log -e $MYPATH/err.log -c "node --max_old_space_size=20" $MYPATH/script_with_node_version_6.js U ...

Challenge: RxJS timeout function not functioning as expected

I am facing an issue with exiting the Observable stream after 3 seconds if there is no new string input. The problem arises when I paste the same value multiple times, as the distinctUntilChanged operator prevents the input stream from progressing. I wan ...

In what ways can we effectively utilize the data retrieved from the api within the map function?

Currently, I am developing a replica of Facebook using react and redux. The post data is fetched from an API (json-server). Each post has a post-menu button that opens the post menu when clicked. However, due to my usage of the map function with the data, ...

Implementing the useState Hook with Material UI Toggle Button Group in React.js

In the App.js file, I am importing Box from "@mui/system", Header from "./components/Header", ProjectList from "./components/ProjectList", CardLayout from "./components/CardLayout", and React, useState from "react". The goal here is to render the ProjectLi ...

Need to know how to invoke a function from an http callback function that resides in a separate file? Simply use the `app.get("/", callbackFun)` method

Directory Organization: testAPI contactDetail dispMobNo.js myModule.js index.js index.js const express = require("express"); const app = express(); const port = process.env.port || 3000; const getCustNo = require("./cont ...

Transform XML2JS by eliminating square brackets around values

Currently, I am utilizing the xml2js node package for parsing an XML feed. Is there a method to avoid having the values enclosed in square brackets? For instance: "reference": ["ABC123"] should appear as "reference": "ABC123" "items": [ { "r ...

Unable to display nested JSON data from API in Vue.js

Having trouble accessing nested properties from API JSON data. The Vue component I'm working on: var profileComponent = { data : function() { return { isError : false, loading : true, users : null, ...

Stopping autoplay in React Swiper when hovering over it

I'm currently struggling to find a way to pause the autoplay function on swiper when hovering over it. Despite my efforts, I have not been able to locate a solution. <Swiper spaceBetween={0} navigation={{ ...

Sign up for a Jquery template event

When utilizing a jquery template, the following HTML markup is being used: <div id="results"> <div class="CommentItem" commentid="33064" id="33064" data-guid="/Profile/Profile.aspx?id=Charliedog33"> <div class="CommentPic" ...

Having trouble with your Discord.js Bot continuously going offline and getting Value errors? Here’s how to resolve it

Why do I keep encountering this error? TypeError: Cannot read property 'size' of undefined at Client.client.on.message (/home/colter/Code/groundskeeper/index.js:38:30) at emitOne (events.js:116:13) at Client.emit (events.js:211:7) at MessageCre ...

Retrieve a file from an Express API using React with the help of Axios

When working with a React client and an Express API, how can the React client download a file sent by the Express API? Issue: If I manually enter the URL into my browser's address bar and hit enter, the file downloads successfully. However, when I ...

The styles in the CSS file are not behaving as expected

Having an issue with my CSS file for the Header.js module. Despite writing rules, only one style is applying. Can anyone help me identify the problem? Thanks in advance! Header.js component import React from 'react'; import '../../../asset/ ...

How can we align the top edge of a div to the center of a circle within a separate div in a responsive manner?

I want to create 2 stacked divs: the first div contains a circular image, and the second div contains text. I want the second div to always cover half of the circle, with its upper edge positioned at the center point of the circle. This is my code: .cov ...

Generating an array of objects using Jquery from XML data

I need assistance with extracting data from XML text nodes stored in a variable and then creating an array of objects using jQuery. The XML data I have is as follows: var header = ['name', 'data1', 'data2']; var data = &apos ...

"Utilize the parent component's functionality by extending/inheriting it

export default function PageTemplate() { return ( <div className="layout"> <LeftMenu /> <div className="content"> <TopMenu /> <div id="other-contents"> ...

The use of the .reset() function in typescript to clear form data may lead to unexpected

I've been trying to use document.getelementbyID().reset(); to reset form values, but I keep running into an error in TypeScript. Property 'reset' does not exist on type 'HTMLElement'. Here's how I implemented it: const resetB ...

When iterating through it, a sorted array in Javascript mutates the window object, but not in any

I am working with Python Django to create a view that returns JSON data to a template. In this template, I initialize a global JavaScript variable like so: <script type="text/javascript"> coordinates = {{ coordinates | safe}} </script> Th ...