我定义了一个人物和故事模式:
@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')
时,作者为null:
stories {
_id: 5f135150e46fa5256a3a1339,
title: 'Casino Royale',
author: null,
__v: 0
}
如何用引用的“个人”文档填充“作者”字段?
答案 0 :(得分:5)
在对 nestjs 中的 mongoose 引用进行大量阅读和测试之后。我认为可以改进接受的答案。我将分 2 个步骤展示这一点。第一步是显示 MongooseSchema 的声明,并包括@illnr 关于作者属性使用 Types.ObjectId
而不是 MongooseSchema.Types.ObjectId
的注释。
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document, Types, Schema as MongooseSchema } from 'mongoose';
@Schema()
export class Story extends Document {
@Prop()
title: string;
@Prop({ type: MongooseSchema.Types.ObjectId , ref: 'Person' })
author: Types.ObjectId
}
export const StorySchema = SchemaFactory.createForClass(Story);
作为第二步,我认为使用 Person 类作为作者属性的类型可以提高可读性,如下所示。
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document, Types, Schema as MongooseSchema } from 'mongoose';
import { Person } from './person.schema'
@Schema()
export class Story extends Document {
@Prop()
title: string;
@Prop({ type: MongooseSchema.Types.ObjectId , ref: 'Person' })
author: Person
}
export const StorySchema = SchemaFactory.createForClass(Story);
答案 1 :(得分:4)
找到了。 我的错误在于定义架构。 应该是:
@Schema()
export class Story extends Document {
@Prop()
title: string;
@Prop({ type: MongooseSchema.Types.ObjectId , ref: 'Person' })
author: MongooseSchema.Types.ObjectId
}