【发布时间】:2020-11-08 09:22:51
【问题描述】:
我定义了一个 Person 和 Story 模式:
@Schema()
export class Person extends Document {
@Prop()
name: string;
}
export const PersonSchema = SchemaFactory.createForClass(Person);
@Schema()
export class Story extends Document {
@Prop()
title: string;
@Prop()
author: { type: MongooseSchema.Types.ObjectId , ref: 'Person' }
}
export const StorySchema = SchemaFactory.createForClass(Story);
在我的服务中,我实现了保存和读取功能:
async saveStory(){
const newPerson = new this.personModel();
newPerson.name = 'Ian Fleming';
await newPerson.save();
const newStory = new this.storyModel();
newStory.title = 'Casino Royale';
newStory.author = newPerson._id;
await newStory.save();
}
async readStory(){
const stories = await this.storyModel.
findOne({ title: 'Casino Royale' })
console.log('stories ',stories);
}
当我运行 readStory() 时,我得到以下输出:
stories {
_id: 5f135150e46fa5256a3a1339,
title: 'Casino Royale',
author: 5f135150e46fa5256a3a1338,
__v: 0
}
当我在查询中添加populate('author') 时,我将作者设为空:
stories {
_id: 5f135150e46fa5256a3a1339,
title: 'Casino Royale',
author: null,
__v: 0
}
如何使用引用的个人文档填充作者字段?
【问题讨论】:
标签: mongoose nestjs mongoose-populate