【问题标题】:How to populate mongoose references in nestjs?如何在nestjs中填充猫鼬引用?
【发布时间】: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


    【解决方案1】:

    以上都不适合我,我必须使用populate()。参考来自https://dev.to/mossnana/nestjs-with-mongoose-populate-4mo7?signin=true

    完整代码和结构的示例 users.service.ts

    import { User, UserDocument } from 'src/schemas/user.schema';
    import { Role, RoleDocument } from 'src/schemas/role.schema';
    
    ...
    
    constructor(
        @InjectModel(User.name) private userModel: Model<UserDocument>,
        @InjectModel(Role.name) private roleModel: Model<RoleDocument>,
        private roleService: RolesService
      ) {}
    
    
    async findOne(id: string) {
        return await this.userModel.findOne({ _id: id }).populate('role', '', this.roleModel).exec();
    }
    

    user.schema.ts

    import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
    import * as mongoose from 'mongoose';
    import { Role } from './role.schema';
    
    export type UserDocument = User & mongoose.Document;
    
    @Schema()
    export class User {
      @Prop({ required: true, type: String })
      email: string;
    
      @Prop({ type: String })
      name: string;
    
      @Prop({ type: mongoose.Schema.Types.ObjectId, ref: 'Role' })
      role: Role;
    }
    
    export const UserSchema = SchemaFactory.createForClass(User);
    

    role.schema.ts

    export type RoleDocument = Role & mongoose.Document;
    
    @Schema()
    export class Role {
      @Prop({ type: String, required: true, unique: true, index: true })
      name: string;
    
      @Prop({ type: [String], required: true })
      permissions: string[];
    }
    
    export const RoleSchema = SchemaFactory.createForClass(Role);
    

    【讨论】:

      【解决方案2】:

      找到了。 我的错误在于定义模式。 应该是:

      @Schema()
      export class Story extends Document {
        @Prop()
        title: string;
          
        @Prop({ type: MongooseSchema.Types.ObjectId , ref: 'Person' })
        author:  MongooseSchema.Types.ObjectId  
      }
      

      【讨论】:

      • 谢谢!在Prop 选项中设置类型是我的问题的解决方案,因为我使用联合类型来进行实际的打字稿类型。顺便说一句:你也可以import { Types } from 'mongoose'; 然后使用author: Types.ObjectId
      • 如何为数组编写这个?我尝试用这样的数组包装:@Prop([{ type: MongooseSchema.Types.ObjectId , ref: 'Person' }])
      • @austinthedeveloper 我不确定您是否可以拥有一组可以自动填充的引用。但我不知道。
      【解决方案3】:

      在对 Nestjs 中的 mongoose 引用进行大量阅读和测试之后。我认为可以改进接受的答案。我将分两步展示这一点。第一步是显示 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 类作为 author 属性的类型会提高可读性,如下所示。

      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);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-06-11
        • 2017-10-11
        • 2019-02-24
        • 2015-07-13
        • 2016-10-10
        • 2021-06-29
        • 1970-01-01
        相关资源
        最近更新 更多