簡體   English   中英

從包含引用的字段中獲取數據

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM