Home > Enterprise >  How can I display the username of a forum?
How can I display the username of a forum?

Time:01-13

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:

You see I have only ref: 'user' and this is grabbing the ObjectId("") from the User.

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,
      deafult: false,
  },

});

Front-end :

As you can see only in {forum.user} there I can see the id from the user but I want his name not the id

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

CodePudding user response:

Since you are using 'ref' to reference the user table. When you are fetching a forum document, use the populate() function in mongoose to get all the user details as a sub-object to the forum document.

example: forumShcema.find({_id:<forum_id>}).populate('user').exec()

CodePudding user response:

Try to retrieve the Forum instance after its creation using the populate method.
This should populate the user attribute with the corresponding User data:

const newForum = new Forum({
    forumName,
    forumDescription,
    user: owner.userID,
  });
  newForum.user = owner;
  await newForum.save();
  
  const note = await Forum.findBy(newForum._id).populate('user').exec();
  
  return res.status(201).json(note);  
  •  Tags:  
  • Related