NestJS - Mongoose 鉴别器密钥不会自动填充
discriminatorKey
不会自动填充。换句话说,我在保存的文档中找不到 kind
字段。
数据库模块
@Global()
@Module({
imports: [
MongooseModule.forFeature([
{
name: User.name,
schema: UserSchema,
discriminators: [
{ name: Fan.name, schema: FanSchema },
],
},
]),
],
exports: [MongooseModule],
})
export class DatabaseModule {}
用户架构
@Schema({ discriminatorKey: 'kind' })
export class User {
@Prop({ enum: [Fan.name], required: true })
kind: string;
@Prop()
displayName: string;
}
export const UserSchema = SchemaFactory.createForClass(User);
粉丝架构
@Schema()
export class Fan {
kind: string;
displayName: string;
}
export const FanSchema = SchemaFactory.createForClass(Fan);
保存文档
const userObj = new Fan();
userObj.displayName = "Sam";
return this.userModel.create(userObj);
The discriminatorKey
won't be filled up automatically. In other words, I cannot find the kind
field on the saved document.
Database Module
@Global()
@Module({
imports: [
MongooseModule.forFeature([
{
name: User.name,
schema: UserSchema,
discriminators: [
{ name: Fan.name, schema: FanSchema },
],
},
]),
],
exports: [MongooseModule],
})
export class DatabaseModule {}
User Schema
@Schema({ discriminatorKey: 'kind' })
export class User {
@Prop({ enum: [Fan.name], required: true })
kind: string;
@Prop()
displayName: string;
}
export const UserSchema = SchemaFactory.createForClass(User);
Fan Schema
@Schema()
export class Fan {
kind: string;
displayName: string;
}
export const FanSchema = SchemaFactory.createForClass(Fan);
Save a Document
const userObj = new Fan();
userObj.displayName = "Sam";
return this.userModel.create(userObj);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我注入了错误的模型,这就是为什么
discriminatorKey
无法自动填充的原因。错误使用
正确使用
I was injecting the wrong model, that's why the
discriminatorKey
couldn't be filled up automatically.Wrong Use
Correct Use