假设我要使用猫鼬构建以下架构:
const userSchema = new Schema({
name: {
firstName: String,
lastName: String
}
})
如何使用NestJS装饰器(@Schema()
和@Prop()
)做到这一点?
我尝试这种方法,但是没有运气:
@Schema()
class Name {
@Prop()
firstName: string;
@Prop()
lastName: string;
}
@Schema()
class User extends Document {
@Prop({ type: Name })
name: Name;
}
我也不想使用raw()
方法。
答案 0 :(得分:3)
这是我的方法,效果很好,不涉及删除@schema():
// Nested Schema
@Schema()
export class BodyApi extends Document {
@Prop({ required: true })
type: string;
@Prop()
content: string;
}
export const BodySchema = SchemaFactory.createForClass(BodyApi);
// Parent Schema
@Schema()
export class ChaptersApi extends Document {
// Array example
@Prop({ type: [BodySchema], default: [] })
body: BodyContentInterface[];
// Single example
@Prop({ type: BodySchema })
body: BodyContentInterface;
}
export const ChaptersSchema = SchemaFactory.createForClass(ChaptersApi);
这样可以正确保存并在架构上设置该选项时显示时间戳记
答案 1 :(得分:0)
尝试从嵌套的“名称”中删除@schema()装饰器,仅将其保留在文档的根目录中。
还请记住在根级别扩展“ mongoose.Document”。
import { Prop, Schema, SchemaFactory, } from '@nestjs/mongoose';
import { Document } from 'mongoose';
class Name {
@Prop()
firstName: string;
@Prop()
lastName: string;
}
@Schema()
class User extends Document {
@Prop({ type: Name })
name: Name;
}
export const userSchema = SchemaFactory.createForClass(user);
答案 2 :(得分:0)
所做的更改:
@Schema
装饰器Document
扩展'mongoose'
user.schema.ts
import { Document } from 'mongoose';
@Schema()
export class User extends Document {
@Prop({ type: Name })
name: Name;
}
export const UserSchema = SchemaFactory.createForClass(User);
name.schema.ts
import { Document } from 'mongoose';
export class Name extends Document {
@Prop({ default: " " })
firstName: string;
@Prop({ default: " " })
lastName: string;
}
答案 3 :(得分:0)
你也可以使用这个。
@Schema()
class User extends Document {
@Prop({ type: { firstName: String, lastName: String })
name: Name;
}
答案 4 :(得分:-1)
首先,在这种情况下,应使用猫鼬模式。简单明了:
export const UserSchema = new mongoose.Schema(
{
name: [UserNameSchema],
},
{
timestamps: true,
},
);
如果您不喜欢这种方法,则应遵循官方文档:
@Prop(raw({
firstName: { type: String },
lastName: { type: String }
}))
details: Record<string, any>;