Fal*_*ort 3 mongoose nestjs typegoose
我目前正在运行代码:
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;
}
Run Code Online (Sandbox Code Playgroud)
我没有找到任何“扩展”模式的方法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;
}
Run Code Online (Sandbox Code Playgroud)
我没有发现任何可以考虑SystemInformation.system @Prop()到SystemInformationContent.
你们知道是否还有其他方法或者raw我是否遗漏了什么?
编辑:我的 NestJS 应用程序的所有类都扩展了 SystemInformation,因此它们看起来都像:
{
...,
system: {
createdAt: 1616778310610,
createdBy: "605e14469d860eb1f0641cad",
editedAt: 0,
createdBy: null,
},
}
Run Code Online (Sandbox Code Playgroud)
找到解决办法了!
我编辑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,
);
Run Code Online (Sandbox Code Playgroud)
然后在 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;
}
Run Code Online (Sandbox Code Playgroud)
现在一切正常,我使用@Schema({ _id: false })删除了 SchemaFactory 生成的 ID,所以我最终在数据库中得到了它:
{
...,
"system": {
"updatedBy": null,
"updatedAt": 0,
"createdAt": 1616847116986,
"createdBy": {
"$oid": "605f210cc9fe3bcbdf01c95d"
}
},
...,
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6744 次 |
| 最近记录: |