[英]Get data from field containing reference
我的“发布”架构如下。
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"}
在 find Query 时,您必须使用populate
Post.find().populate('users')
这里 users 是用户集合
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.