目前,当向 findOneAndUpdate 提供 id 时,它不会返回自动生成的 id。
所以我创建了扩展方法来克服这个问题。但是打字稿抱怨打字。需要帮助。
我创建了如下扩展方法。
declare module 'mongoose' {
interface Model<T>
extends NodeJS.EventEmitter,
AcceptsDiscriminator {
findOneAndUpsert<T>(
filter?: FilterQuery<T>,
update?: UpdateQuery<T>,
options?: QueryOptions | null,
callback?: (err: any, doc: T | null, res: any) => void,
): Promise<QueryWithHelpers<T | null, T>>; // Here I am getting error as "Type 'T' does not satisfy the constraint 'Document<any, {}>'"
}
}
mongoose.model.prototype.findOneAndUpsert = async function <
T extends mongoose.Document<any, {}>
>(
filter?: FilterQuery<T>,
update?: UpdateQuery<T>,
options?: QueryOptions | null,
callback?: (err: any, doc: T | null, res: any) => void,
): Promise<QueryWithHelpers<T | null, T>> {
const model = this as mongoose.Model<T>;
if (filter.id) {
return model.findOneAndUpdate(filter, update);
} else {
return model.findById((await model.create((update as any).$set)).id);
}
};
我想像下面这样使用它。
datasource = await DatasourceModel(
await this.projectContext,
).findOneAndUpsert(
{ id: datasource.id },
{
$set: {
name: datasource.name,
type: datasource.type,
source: datasource.source,
},
},
);
我的数据源模型如下所示。
export class Datasource extends ModelBase {
@prop()
authTokenId?: number;
}
export const DatasourceModel = (connection: Connection) => {
return getModelForClass(Datasource, connection);
};
在声明期间我收到错误,因为“类型'T'不满足约束'Document<any,{}>'”?
如果我写"T extends mongoose.Document<any, {}>"
在模型声明中,那么不会给出错误,但是在调用该方法期间它会给出错误"Property 'name' is missing in type 'Document<any, {}>' but required in type 'Datasource'"
谁能帮助我在这里需要做的事情?