NestJS Mongo引用未正确保存



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

让我再解释一下情况。我有一个名为SystemInformation的类,它包含诸如对象是何时创建的或由谁创建的之类的字段。应用程序的所有其他模式都扩展了这个类。字段";createdBy";是对用户模式的引用(它还扩展了SystemInformation(。当我保存一个对象时,有效负载包含创建记录的用户的id。但当我从Compass中查看mongo数据库时,我会将字段视为字符串,但从未将其视为具有官方格式的ref,其格式看起来像:

{ "$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();

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

,但从未作为正式格式的ref,看起来像

mongoose使用这样的格式,mongoose引用的工作方式是将id直接保存为目标架构上的类型(objectid表示objectid,string表示string(,为了查找id被分配到哪个数据库,它可能会在什么连接上使用模型&数据库它是在上创建的

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

相关内容

最新更新