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

标签 mongodb reference find fetch objectid

我的“帖子”架构如下。

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/

相关文章:

javascript - Mongo $lookup 返回空数组

在 Docker 上安装 Mongodb

python - 在Python中复制复合对象

将一个指针的引用复制到另一个指针 C

c# - 找到的程序集的 list 定义与程序集引用不匹配

opencv - 在 JavaCV 或 OPENCV 中查找轮廓

javascript - jQuery 从类数组中查找类名值

python - Pandas - 找到第一次出现

java - 将mongodb文档解析为字符串变量

mongodb - 使用 MongoTemplate 时是否可以动态设置特定查询的读取首选项?