[英]Mongoose populate referencing object id, not the object itself
這是我的用戶 model 的一部分:
const Group = require("./Group")
...
groups: {
type: [{ type: Schema.ObjectId, ref: Group }],
default: [],
},
這是我的組 model:
module.exports = mongoose.model(
"Group",
new Schema(
{
name: {
type: String,
required: true,
unique: true,
},
/**
* Array of User ObjectIDs that have owner rights on this group
*/
owners: {
type: [{ type: Schema.ObjectId, ref: User }],
default: [],
},
},
{
timestamps: true,
}
)
)
這是我正在運行以嘗試填充的代碼:
const user = await (await User.findOne({ _id: ... })).execPopulate("Group")
console.log(user.groups)
我的 console.log 正在輸出一個object IDs數組,當我想要 output 一個實際的 Group 文檔時。
我嘗試將我的ref
更改為使用字符串( "Group"
),我嘗試以不同的方式安排我的查詢等。我不確定 go 是如何做到這一點的。
如果這是重復的,請提前道歉,我已盡力搜索,但無法真正找到適合我的解決方案。
我正在嘗試在用戶 model 和組 model 之間創建“鏈接”。 在我的console.log 中,我希望它以output 一個組文件; 但它輸出一個 object ID(這是它在數據庫中的原始存儲方式,這意味着 ZCCADCDEDB567ABAE643E15DCF0974E503Z 沒有正確轉換它)
當您更改execPopulate
以populate
時:
async function findUserAndPopulate(userId){
const response = await User.findOne({
_id: userId,
}).populate('groups')
console.log("response",response)
}
你得到了:
{
groups: [
{
owners: [Array],
_id: 5ecc637916a2223f15581ec7,
name: 'Crazy',
createdAt: 2020-05-26T00:31:53.379Z,
updatedAt: 2020-05-26T00:31:53.379Z,
__v: 0
}
],
_id: 5ecc6206820d583b99b6b595,
fullname: 'James R',
createdAt: 2020-05-26T00:25:42.948Z,
updatedAt: 2020-05-26T00:36:12.186Z,
__v: 1
}
所以你可以訪問user.groups
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.