我的“帖子”架构如下。
export const postSchema = new Schema({
authorId: { type: ObjectId, required: true },
images: { type: [String], required: true },
note: { type: Number, default: null }, // maybe an "Note" documents array
description: { type: String, required: true },
comments: { type: [ObjectId], default: [] },
});
authorId 字段包含具有以下结构的用户文档的 ID:
export const userSchema = new Schema({
name: { type: String, required: true },
email: { type: String, required: true },
password: { type: String, required: true },
stars: { type: Number, default: 0 },
subscribers: { type: Number, default: 0 },
subscriptions: { type: Number, default: 0 },
avatar: {
type: String,
default: `http://localhost:4545/assets/images/avatars/default_avatar.jpg`,
},
posts: { type: [ObjectId], default: [] },
});
当我使用以下方式获取我的帖子时:
const posts = await Post.find()
我想获取引用的用户(帖子作者)的“name”、“avatar”和“_id”字段。
我尝试在我的帖子上映射以使用authorId 字段获取作者数据,但没有成功。我想用聚合来做到这一点,但我不知道。
非常感谢。
最佳答案
您必须在 postSchema
中使用 ref
,例如
authorId: { type: ObjectId, required: true , ref: "users"}
在查找查询时,您必须使用populate
Post.find().populate('users')
这里的users是用户集合
关于mongodb - 从包含引用的字段获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68327706/