我试图在NestJS中继承Mongoose Schemas或SchemaDefitions,但是我没有太多的运气。
我这样做是为了共享基本和常见的模式定义细节,例如我们附加到每个实体的虚拟('id')和nonce。每个模式定义都应该有自己的Mongo集合,所以鉴别器不起作用。
我尝试通过以下不同的方式实现这一点。
首先,我定义了以下基本模式定义:
base.schema.ts
我这样做是为了共享基本和常见的模式定义细节,例如我们附加到每个实体的虚拟('id')和nonce。每个模式定义都应该有自己的Mongo集合,所以鉴别器不起作用。
我尝试通过以下不同的方式实现这一点。
首先,我定义了以下基本模式定义:
base.schema.ts
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document, Types } from 'mongoose';
import { TimeStamps } from './timestamps.schema';
export type BaseDocument = BaseSchemaDefinition & Document;
@Schema({
toJSON: {
virtuals: true,
transform: function (doc: any, ret: any) {
delete ret._id;
delete ret.__v;
return ret;
},
},
})
export class BaseSchemaDefinition {
@Prop({
type: Types.ObjectId,
required: true,
default: Types.ObjectId,
})
nonce: Types.ObjectId;
@Prop()
timestamps: TimeStamps;
}
我随后继承架构定义并创建架构,以便在我的服务和控制器中稍后使用,方式如下:
person.schema.ts
import { Prop, SchemaFactory } from '@nestjs/mongoose';
import * as mongoose from 'mongoose';
import { Document } from 'mongoose';
import { Address } from './address.schema';
import { BaseSchemaDefinition } from './base.schema';
export type PersonDocument = PersonSchemaDefintion & Document;
export class PersonSchemaDefintion extends BaseSchemaDefinition {
@Prop({ required: true })
first_name: string;
@Prop({ required: true })
last_name: string;
@Prop()
middle_name: string;
@Prop()
data_of_birth: Date;
@Prop({ type: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Address' }] })
addresses: [Address];
}
const PersonSchema = SchemaFactory.createForClass(PersonSchemaDefintion);
PersonSchema.virtual('id').get(function (this: PersonDocument) {
return this._id;
});
export { PersonSchema };
这导致我只能创建和获取在BaseSchemaDefinition中定义的属性。
{ "timestamps": { "deleted": null, "updated": "2021-09-21T16:55:17.094Z", "created": "2021-09-21T16:55:17.094Z" }, "_id": "614a0e75eb6cb52aa0ccd026", "nonce": "614a0e75eb6cb52aa0ccd028", "__v": 0 }
其次,我尝试通过使用此处描述的方法继承Mongoose模式(不同的MongoDB集合)来实现继承。
base.schema.ts
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document, Types } from 'mongoose';
import { TimeStamps } from './timestamps.schema';
export type BaseDocument = BaseSchemaDefinition & Document;
@Schema({
toJSON: {
virtuals: true,
transform: function (doc: any, ret: any) {
delete ret._id;
delete ret.__v;
return ret;
},
},
})
export class BaseSchemaDefinition {
@Prop({
type: Types.ObjectId,
required: true,
default: Types.ObjectId,
})
nonce: Types.ObjectId;
@Prop()
timestamps: TimeStamps;
}
const BaseSchema = SchemaFactory.createForClass(BaseSchemaDefinition);
BaseSchema.virtual('id').get(function (this: BaseDocument) {
return this._id;
});
export { BaseSchema };
person.schema.ts
import { Prop } from '@nestjs/mongoose';
import * as mongoose from 'mongoose';
import { Document } from 'mongoose';
import { Address } from './address.schema';
import { BaseSchema, BaseSchemaDefinition } from './base.schema';
export type PersonDocument = PersonSchemaDefintion & Document;
export class PersonSchemaDefintion extends BaseSchemaDefinition {
@Prop({ required: true })
first_name: string;
@Prop({ required: true })
last_name: string;
@Prop()
middle_name: string;
@Prop()
data_of_birth: Date;
@Prop({ type: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Address' }] })
addresses: [Address];
}
export const PersonSchema = Object.assign(
{},
BaseSchema.obj,
PersonSchemaDefintion,
);
输出结果相同,但不确定为什么继承没有生效。
以下是使用模式构建模型的服务代码:
person.service.ts
import { Model } from 'mongoose';
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import {
PersonSchemaDefintion,
PersonDocument,
} from 'src/schemas/person.schema';
import { TimeStamps } from 'src/schemas/timestamps.schema';
@Injectable()
export class PersonService {
constructor(
@InjectModel(PersonSchemaDefintion.name)
private personModel: Model<PersonDocument>,
) {}
async create(
personModel: PersonSchemaDefintion,
): Promise<PersonSchemaDefintion> {
personModel.timestamps = new TimeStamps();
const createdPerson = new this.personModel(personModel);
return createdPerson.save();
}
async update(
id: string,
changes: Partial<PersonSchemaDefintion>,
): Promise<PersonSchemaDefintion> {
const existingPerson = this.personModel
.findByIdAndUpdate(id, changes)
.exec()
.then(() => {
return this.personModel.findById(id);
});
if (!existingPerson) {
throw Error('Id does not exist');
}
return existingPerson;
}
async findAll(): Promise<PersonSchemaDefintion[]> {
return this.personModel.find().exec();
}
async findOne(id: string): Promise<PersonSchemaDefintion> {
return this.personModel.findById(id).exec();
}
async delete(id: string): Promise<string> {
return this.personModel.deleteOne({ _id: id }).then(() => {
return Promise.resolve(`${id} has been deleted`);
});
}
}
如有需要,我可以提供更多细节。