【发布时间】:2023-03-17 04:44:01
【问题描述】:
我已经创建了用户架构,我正在使用不同用户发布的 cmets 存储用户详细信息。
当前数据架构。
{
_id: '1233333',
name: 'John',
profileImage: 'http:/test.com',
coments: [{
commentBy: ObjectId(UserId),
comment: 'good '
}, {
commentBy: ObjectId(UserId),
comment: 'good'
}
]
}
当我获取用户数据时,我想在 cmets 数组中获取用户名、个人资料图像 URL,我没有存储 profileimageURL、名称,因为用户会随时更新用户数据。
我想要预期的数据
{
_id: '1233333',
name: 'John',
profileImage: 'http:/test.com',
coments: [{
commentBy: ObjectId(UserId),
comment: 'good ',
profileImage: 'http:/test.com',
name : 'John'
}, {
commentBy: ObjectId(UserId),
comment: 'good ',
profileImage: 'http:/test.com',
name : 'Tim'
}
]
}
请告诉我查询以一次性获取数据..请告知
【问题讨论】:
-
有两个选项您可以使用
aggregation lookup查询或virtual查询进行聚合查询https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/按照此链接和虚拟查询UserSchema.virtual('commentBy',{ ref: 'user',//this the collection name localField: 'coments.commentBy', foreignField: '_id', justOne:true }); UserSchema.set('toObject', { virtuals: true }); UserSchema.set('toJSON', { virtuals: true });
标签: node.js mongoose mongoose-schema