【发布时间】:2021-08-26 03:28:07
【问题描述】:
目前当 id 提供给 findOneAndUpdate 时,它不会返回自动生成的 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
如果我在模型声明中写"T extends mongoose.Document<any, {}>",那么不会给出错误,但是在调用该方法时它会给出错误"Property 'name' is missing in type 'Document<any, {}>' but required in type 'Datasource'"
任何人都可以帮忙解决我在这里需要做的事情吗?
【问题讨论】:
-
您使用的版本是什么(typescript、mongoose、typegoose),您是否已经尝试将选项
new: true添加到findOneAndUpdate -
tpyegoose 5.9.1,打字稿 4.2.4,猫鼬 5.12.7
-
试过新的:真。但它也没有返回新生成的 ID。它返回空 ID。
-
似乎以下是相关的...stackoverflow.com/questions/17244363/…
标签: node.js typescript mongodb mongoose typegoose