【问题标题】:NestJS Mongo references not saved properlyNestJS Mongo 引用未正确保存
【发布时间】:2021-06-09 20:15:56
【问题描述】:

我正在使用 Mongo 开发 NestJS 后端,但我在使用 mongo 引用时遇到了困难。

让我再解释一下情况。 我有一个名为 SystemInformation 的类,其中包含对象何时创建或由谁创建等字段。 应用程序的所有其他模式都扩展了这个类。 字段“createdBy”是对用户模式的引用(也扩展了 SystemInformation)。 当我保存对象时,有效负载包含创建记录的用户的 ID。 但是当我从 Compass 中查看 mongo 数据库时,我将该字段视为一个字符串,但从不作为官方格式的参考,如下所示:

    { "$ref" : <value>, "$id" : <value>, "$db" : <value> }

以下是正在使用的代码的相关部分:

这是系统类和架构:

@ObjectType()
@Schema()
class SystemContent {
  @Field()
  @Prop({ required: true })
  createdAt: number;

  @Field()
  @Prop({ default: 0 })
  updatedAt: number;

  @Field()
  @Prop({ required: true, type: mongoose.Schema.Types.ObjectId, ref: 'User' })
  createdBy: string;

  @Field()
  @Prop({ default: '' })
  updatedBy: string;
}

@ObjectType()
@Schema()
export class SystemInformation {
  @Field()
  @Prop({ required: true })
  system: SystemContent;
}

User 类作为我的扩展实现的示例:

@Schema()
export class User extends SystemInformation {
  id: string;

  @Prop({ required: true, unique: true })
  username: string;

  @Prop({ required: true, unique: true })
  email: string;

  @Prop({ required: true })
  hash: string;

  @Prop({ default: false })
  verified: boolean;

  @Prop({ default: false })
  enabled: boolean;

  @Prop({ default: 0 })
  bruteforce: number;
}
export const UserSchema = SchemaFactory.createForClass(User);
export type UserDocument = User & Document;

保存到mongo的payload和函数是:

const payload = {
  ...
  system: {
    createdBy: '601c12060164023d59120cf43',
    createdAt: 0,
  },
};
const result = await new this.model(payload).save();

我想知道我做错了什么,你们能帮帮我吗?

【问题讨论】:

    标签: mongodb mongoose nestjs typegoose


    【解决方案1】:

    但从不作为看起来像官方格式的参考

    mongoose 不使用这种格式,mongoose 引用通过将 id 直接保存为它在目标模式上的类型(objectid 为 objectid,字符串为字符串)来工作,并查找分配了 id 的 db,它可能在创建它的连接和数据库上使用模型

    PS:typegoose引用可以用public property: Ref&lt;TargetClass&gt;表示
    PPS:将TargetClassDocument组合在一起的官方typegoose类型称为DocumentType&lt;TargetClass&gt;

    【讨论】:

    • 嘿伙计,谢谢你的回答!我希望有一个更简单易懂的数据库,但显然 mongoose 不是那样 无论如何感谢您的启发!
    猜你喜欢
    • 2013-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-29
    • 1970-01-01
    • 2019-03-14
    相关资源
    最近更新 更多