I want to find out how I can display the username of a user. For example user admin posts a forum, then I would see Created By: admin on the forum page, instead I can only fish out the ID.
I don't know a much about mongoose and I need someone who is familiar with it.
My Forum Model:
const forumSchema = ({
forumName: {
type: String,
required: true,
},
forumDescription: {
type: String,
required: true,
},
user: {
type: Schema.Types.ObjectId,
ref: 'user',
},
});
How I create a Note:
exports.create = async (req, res) => {
const { forumName, forumDescription } = req.body;
const token = req.token;
const forumExist = await Forum.findOne({ forumName: req.body.forumName });
if (forumExist) {
return res.status(400).send("Forum Exists already.");
}
try {
const owner = await User.findOne({ userID: token.userID });
if (!forumName || !forumDescription) {
return res.status(400).send('Not all fields filled in');
} else {
const newForum = new Forum({
forumName,
forumDescription,
user: owner.userID,
});
newForum.user = owner;
await newForum.save();
const note = await Forum.find().populate('user').lean();
return res.status(201).json(note);
}
} catch (err) {
return res.status(400).send(err);
}
};
If I post with Postman I got this ..:
[
{
"_id": "61b892c383af6eecd758346e",
"forumName": "Mein erstes Forum Admin 2",
"forumDescription": "Das ist ein erstes Forum, das ich im Rahmen der Tests angelegt habe.",
"published_on": "December 14, 2021 1:47 PM",
"user": null,
"__v": 0
},
{
"_id": "61e16a31bd9633523ef74ce2",
"forumName": "testtest7",
"forumDescription": "testing.",
"published_on": "January 14, 2022 1:11 PM",
"user": {
"_id": "61dd83db2b8b9b6e2a8e7f0b",
"userID": "admin",
"userName": "admin",
"password": "$2b$10$qwAZspGbchBkZ6eoe8ODxOiLeOrK2J3cltrLMKlVB/6TRhL5e1qAy",
"isAdministrator": true,
"__v": 0
},
"__v": 0
}
]
And if I want to display it normally it should be in the Frontend this way ..
const noteList = useSelector(state => state.noteList);
const { notes } = noteList;
console.log(noteList);
const [messages, setMessages] = useState([]);
useEffect(()=> {
dispatch(listForum());
}, [dispatch, history]);
console.log(notes);
return (
<MainScreen title={`List of Forum`}>
{notes &&
notes?.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}
but there is no userName .. only if write forum.user I got the id of the user ..