【问题标题】:How can I display the username of a forum?如何显示论坛的用户名?
【发布时间】:2022-01-13 13:17:46
【问题描述】:

我想了解如何显示用户的用户名。例如用户 admin 发布了一个论坛,然后我会在论坛页面上看到 Created By: admin,而我只能找出 ID。

我对猫鼬了解不多,我需要熟悉它的人。

我的论坛模型:

你看我只有 ref: 'user' 并且这是从用户那里获取 ObjectId("")。

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")
   },
});

我的用户模型:

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

});

前端:

正如你只能在 {forum.user} 看到的那样,我可以看到用户的 id,但我想要他的名字而不是 id

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

【问题讨论】:

  • 能否把负责返回论坛对象的方法发到后台?
  • @LucaPizzini 我编辑了它

标签: javascript node.js reactjs mongodb mongoose


【解决方案1】:

因为您使用 'ref' 来引用用户表。在获取论坛文档时,使用 mongoose 中的 populate() 函数将所有用户详细信息作为论坛文档的子对象获取。

示例:forumShcema.find({_id:&lt;forum_id&gt;}).populate('user').exec()

【讨论】:

  • 我创建了一个论坛,但数据库中只有用户的对象 ID 没有更多
【解决方案2】:

尝试使用populate 方法在创建后检索Forum 实例。
这应该使用相应的User 数据填充用户属性:

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);  

【讨论】:

  • 创建论坛后会发生什么?
猜你喜欢
  • 2017-05-20
  • 2012-10-28
  • 2011-01-18
  • 1970-01-01
  • 2011-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多