0

我正在使用 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 的有效负载和功能是:

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

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

4

1 回答 1

0

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

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

PS:typegoose引用可以用public property: Ref<TargetClass>
PPS表示:官方的typegoose类型来组合TargetClassDocument调用DocumentType<TargetClass>

于 2021-03-14T13:24:22.153 回答