填充子集合
Populate child collection
这是 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,
});
所以,person
有 stories
的列表,当我们获取 persons
时,我们可以使用 populate('stories')
包含 stories
。到目前为止一切顺利。
但是为了让它起作用,在创建 Story
时,我们需要将 storyId
添加到 Person
中的 stories
列表中。我来自 SQL
背景,不需要这样做,它会根据 Story
上的 authorId
自动找到相关的 stories
。
所以问题是,是否可以用同样的方法在这里完成,而不需要在 Person
上更新 stories
属性?
我找到了一个解决方案,它叫做 virtual property
:
AuthorSchema.virtual('posts', {
ref: 'BlogPost',
localField: '_id',
foreignField: 'author'
});
这样我就可以在查询中填充 posts
而无需在 Author/Person
模式中保存 postIds
。
这是 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,
});
所以,person
有 stories
的列表,当我们获取 persons
时,我们可以使用 populate('stories')
包含 stories
。到目前为止一切顺利。
但是为了让它起作用,在创建 Story
时,我们需要将 storyId
添加到 Person
中的 stories
列表中。我来自 SQL
背景,不需要这样做,它会根据 Story
上的 authorId
自动找到相关的 stories
。
所以问题是,是否可以用同样的方法在这里完成,而不需要在 Person
上更新 stories
属性?
我找到了一个解决方案,它叫做 virtual property
:
AuthorSchema.virtual('posts', {
ref: 'BlogPost',
localField: '_id',
foreignField: 'author'
});
这样我就可以在查询中填充 posts
而无需在 Author/Person
模式中保存 postIds
。