【问题标题】:discriminators/ single-collection-inheritance with nestjs/mongoose判别器/带有nestjs/mongoose的单一集合继承
【发布时间】:2021-02-04 02:22:24
【问题描述】:

问题

您好,我正在尝试使用nestjsmongo 中创建用户集合。我希望有几个方案可以从一个基本模式继承,并有一个可以扩展的基本服务。

因为nestjs/mongoose没有这样的功能我尝试自己实现,主要问题是我定义的唯一键在集合中不是唯一的

一些代码

这里我定义了两个方案

import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';

export type UserDocument = User & Document;

@Schema()
export class User {
    @Prop({ unique: true, type: 'string' })
    username: string;

    @Prop()
    password: string;

    @Prop()
    created: Date;

    @Prop()
    updated: Date;

    @Prop()
    type: string;

    @Prop()
    name?: string

    // roles: Role[];
}

export const UserSchema = SchemaFactory.createForClass(User);


@Schema()
export class EUser extends User {
    @Prop()
    language: string;
}

export const EUserSchema = SchemaFactory.createForClass(EUser);
export type EUserDocument = EUser & Document;

不,为了将它们保存到同一个集合中,我将 mongooseModule.forfeature 配置为使用以下内容:


@Module({
  imports: [MongooseModule.forFeature([
    {
      name: EUser.name, schema: EUserSchema, collection: 'users'
    }
  ])
  ]})

因此它将所有内容保存到同一个集合中,但不关心(甚至不创建!)唯一索引。

【问题讨论】:

    标签: node.js mongoose nestjs


    【解决方案1】:

    我找到了这个在服务中加载索引的函数

    constructor(@InjectModel(User.name) protected UserModel: Model<UserDocument>) {
    
       this.UserModel.createIndexes()
    }
    

    问题解决了:)

    【讨论】:

      猜你喜欢
      • 2021-11-15
      • 1970-01-01
      • 2020-11-11
      • 1970-01-01
      • 1970-01-01
      • 2023-03-14
      • 2012-01-11
      • 2012-01-18
      • 2012-03-14
      相关资源
      最近更新 更多