我目前正在运行代码:
export class SystemInformationContent {
createdAt: number;
createdBy: User | mongoose.Schema.Types.ObjectId | null;
updatedAt?: number;
updatedBy?: User | mongoose.Schema.Types.ObjectId | null;
}
@Schema()
export class SystemInformation {
@Prop(
raw({
createdAt: { type: Number, required: true },
createdBy: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
updatedAt: { type: Number, default: 0 },
updatedBy: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
default: null,
},
}),
)
system: SystemInformationContent;
}
我没有找到任何“扩展”SystemInformationContent
架构的方法所以使用了raw()
@Prop()
中的函数装饰器,但我想知道是否有办法做这样的事情:
export class SystemInformationContent {
@Prop({ required: true })
createdAt: number;
@Prop({ type: mongoose.Schema.Types.ObjectId, ref: 'User' })
createdBy: User | mongoose.Schema.Types.ObjectId | null;
@Prop({ default: 0 })
updatedAt?: number;
@Prop({ type: mongoose.Schema.Types.ObjectId, ref: 'User', default: null })
updatedBy?: User | mongoose.Schema.Types.ObjectId | null;
}
@Schema()
export class SystemInformation {
@Prop(???)
system: SystemInformationContent;
}
我没有发现任何可以放入 SystemInformation.system
的东西@Prop()
考虑到 SystemInformationContent
的模式.
你们知道除了raw
还有其他方法吗?或者如果我遗漏了什么?
编辑:我的 NestJS 应用程序的所有类都扩展了 SystemInformation,因此它们看起来都像:
{
...,
system: {
createdAt: 1616778310610,
createdBy: "605e14469d860eb1f0641cad",
editedAt: 0,
createdBy: null,
},
}
最佳答案
找到解决方案!
我将 SystemInformationContent
编辑为:
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import * as mongoose from 'mongoose';
import { User } from '~/schemas/user.schema';
@Schema({ _id: false })
export class SystemInformationContent {
@Prop({ type: Number, required: true })
createdAt: number;
@Prop({ type: mongoose.Schema.Types.ObjectId, ref: 'User' })
createdBy: User;
@Prop({ type: Number, default: 0 })
updatedAt?: number;
@Prop({
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
default: null,
})
updatedBy?: User;
}
export const SystemInformationContentSchema = SchemaFactory.createForClass(
SystemInformationContent,
);
然后在 SystemInformation 中我编辑为:
import { Prop, Schema } from '@nestjs/mongoose';
import {
SystemInformationContent,
SystemInformationContentSchema,
} from '~/schemas/systemInformationContent.schema';
@Schema()
export default class SystemInformation {
@Prop({ required: true, type: SystemInformationContentSchema })
system: SystemInformationContent;
}
现在一切正常,我使用 @Schema({ _id: false })
删除了 SchemaFactory 生成的 ID,所以我最终在数据库中得到了它:
{
...,
"system": {
"updatedBy": null,
"updatedAt": 0,
"createdAt": 1616847116986,
"createdBy": {
"$oid": "605f210cc9fe3bcbdf01c95d"
}
},
...,
}
关于mongoose - NestJS MongoDB 嵌套对象模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66779350/