简体   繁体   English

从包含引用的字段中获取数据

[英]Get data from field containing reference

My "Post" schema is the following.我的“发布”架构如下。

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: [] },
});

the authorId field contains the Id of a User document that have the following structure : 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: [] },
});

when I fetch my posts using:当我使用以下方法获取我的帖子时:

const posts = await Post.find()

I would like to get the "name" , "avatar" and "_id" fields of the referenced User (author of the post).我想获取引用用户(帖子作者)的 "name" 、 "avatar" 和 "_id" 字段。

I tried to map on my posts to fetch the author data using the authorId field without success.我试图在我的帖子上映射以使用 authorId 字段获取作者数据,但没有成功。 I would like to do it with agregates but I don't know it.我想用聚合来做,但我不知道。

thanks a lot.多谢。

you have to use ref in postSchema like你必须在postSchema使用ref

authorId: { type: ObjectId, required: true , ref: "users"}

and while find Query you have to use populate在 find Query 时,您必须使用populate

Post.find().populate('users')

here users is user collection这里 users 是用户集合

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM