这是我的用户模型的一部分:
const Group = require("./Group")
...
groups: {
type: [{ type: Schema.ObjectId, ref: Group }],
default: [],
},
这是我的小组模型:
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正在输出对象ID的数组。
[我尝试将ref
更改为使用字符串("Group"
),尝试将查询安排为其他方式,等等。我不确定如何去做。
如果这是重复的话,请提前道歉,我已尽力进行搜索,但实际上找不到适合我的解决方案。
我正在尝试在用户模型和组模型之间创建“链接”。我希望在console.log中,它可以输出一个Group文档;但它会输出一个对象ID(这是将其原始存储在数据库中的方式,这意味着Mongoose无法正确转换它)]
当您将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