【发布时间】:2019-06-22 16:46:08
【问题描述】:
我在我的 MongoDB 集合中实现了软删除功能。现在我想将 mongoose 库版本从 4 更新到 5 时遇到问题。问题是 mongoose 库的 5.xy 版本本身支持软删除功能(具有isDeleted() 方法),这会干扰我自己的@987654324 @字段。
我有这样的事情:
export class Factory<E> {
private readonly _model: Model<Document & E>;
public get model(): Model<Document & E> {
return this._model;
}
constructor(config: IFactoryConfiguration) {
// ...
let schema: Schema = new Schema(this.definition);
this._model = this.connection.model<Document & E>(this.name, schema);
}
}
那么我有:
export class UserFactory extends Factory<IUser> {
constructor(connection: Connection) {
super({
connection: connection,
name: 'User',
definition: UserSchema
});
}
}
还有:
export const UserSchema: SchemaDefinition = {
// ...
isDeleted: {
type: Boolean,
default: false
} // ...
}
IUser 具有 isDeleted: boolean; 等属性。
现在,我想在每次启动服务器时创建/更新系统用户:
let system = await this.factories.user.model.findOne({
'isSystem': true
});
if (!system) {
system = new this.factories.user.model();
system.isSystem = true;
system.isDeleted = true; <-- error here
await system.save();
}
问题是我的集合模型中有isDeleted 属性(在本例中为IUser),但猫鼬在它的Document 类中有isDeleted() 方法。因为我有Document & IUser 的Intersection Type,所以我在这里受到了一些干扰。我得到的错误是:
错误:(239, 7) TS2322: 类型 'true' 不能分配给类型 '({ (isDeleted: boolean): void; (): boolean; } & false) | ({ (isDeleted: boolean): void; (): boolean; } & true)'。
因为有isDeleted(): boolean;方法(看看here)。我该如何解决这个问题?
具体来说,我想更新
"mongoose": "^4.13.17",
"@types/mongoose": "^4.7.23",
到
"mongoose": "^5.4.7",
"@types/mongoose": "^5.3.10",
我正在使用
"typescript": "^3.2.2",
【问题讨论】:
标签: node.js mongodb typescript express mongoose