我正在使用 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();
我想知道我做错了什么,你们能帮帮我吗?