我想知道如何顯示用戶的用戶名。例如,用戶 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>
uj5u.com熱心網友回復:
由于您使用 'ref' 來參考用戶表。在獲取論壇檔案時,使用 mongoose 中的 populate() 函式將所有用戶詳細資訊作為論壇檔案的子物件獲取。
例子: forumShcema.find({_id:<forum_id>}).populate('user').exec()
uj5u.com熱心網友回復:
嘗試Forum使用該populate方法在創建實體后檢索實體。
這應該使用相應的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);
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/409810.html
標籤:
上一篇:我的電子郵件表單提交條件不起作用
下一篇:大型表單上的雙向資料系結
