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>