【问题标题】:Populate child collection填充子集合
【发布时间】:2022-01-15 07:47:57
【问题描述】:

这是 mongoose 文档中关于填充的示例:

const personSchema = Schema({
  _id: Schema.Types.ObjectId,
  name: String,
  age: Number,
  stories: [{ type: Schema.Types.ObjectId, ref: 'Story' }]
});

const storySchema = Schema({
  author: { type: Schema.Types.ObjectId, ref: 'Person' },
  title: String,
});

所以,personstories 的列表,当我们获取persons 时,我们可以使用populate('stories') 包含stories。到目前为止一切顺利。

但为了让它工作,在创建Story 时,我们需要将storyId 添加到stories 列表中的Person。我来自SQL背景,不需要这样做,它会根据Story上的authorId自动找到相关的stories

所以问题是,可以在这里以相同的方式完成,而无需更新Person 上的stories 属性吗?

【问题讨论】:

  • 清晰性:person 架构将名称与阅读的 0 个或多个故事(或其他)相关联。不是所有的名字都是作者——但是story 有一个作者并且必须出现在person 中。好的,但这是否意味着作者作为个人必须在故事中拥有自己的故事?如果这是 SQL,您将首先插入一个新人物,然后插入一个作者 = 新人物的新故事。除了推送故事数组与插入之外,这里有什么不同?

标签: mongodb mongoose nestjs


【解决方案1】:

我找到了一个解决方案,它叫virtual property

AuthorSchema.virtual('posts', {
  ref: 'BlogPost',
  localField: '_id',
  foreignField: 'author'
});

这样我可以在查询中填充posts 而无需将postIds 保存在Author/Person 架构中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-01
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 2017-09-07
    相关资源
    最近更新 更多