Mongoose + TypeScript:有条件地在模型上找到()文档抛出错误:联合类型有签名,但没有一个相互兼容

Posted

技术标签:

【中文标题】Mongoose + TypeScript:有条件地在模型上找到()文档抛出错误:联合类型有签名,但没有一个相互兼容【英文标题】:Mongoose + TypeScript: Conditionally find() documents on model throws error: Union type has signatures, but none are compatible with each other 【发布时间】:2022-01-06 16:32:17 【问题描述】:

我正在尝试在我的 TypeScript 代码中有条件地访问 mongoose 模型。任何人都知道如何解决这个 TypeScript 错误? Each member of the union type has signatures, but none of those signatures are compatible with each other

条件模型上的.find() 会抛出错误。


interface PictureDocument extends Document 
    paint: string;

interface VideoDocument extends Document 
    duration: number;


const PictureSchema = new Schema<PictureDocument>( paint: String );
const VideoSchema = new Schema<VideoDocument>( duration: Number );

const PictureModel = model<PictureDocument>("video", PictureSchema);
const VideoModel = model<VideoDocument>("video", VideoSchema);

const MY_CONDITION = "picture";

const getDocuments = async (condition: "picture" | "video") => 
    const model = condition === "picture" ? PictureModel : VideoModel; // <--- Here I conditionally get my model to execute queries on

    return await model.find().exec(); // <--- .find() throws TS error here
;

getDocuments(MY_CONDITION);
This expression is not callable.
  Each member of the union type ' (callback?: ((err: any, res: VideoDocument[]) => void) | undefined): DocumentQuery<VideoDocument[], VideoDocument, >; (conditions: FilterQuery<...>, callback?: ((err: any, res: VideoDocument[]) => void) | undefined): DocumentQuery<...>; (conditions: FilterQuery<...>, projection?: any, callback?: ((err: any, res:...' has signatures, but none of those signatures are compatible with each other.

【问题讨论】:

【参考方案1】:

好的,实际上它很简单,我认为这是 TypeScript 中联合类型问题的常见解决方案

const model: Model<PictureDocument | VideoDocument> = condition === "picture" ? PictureModel : VideoModel;

通过在变量声明中添加类型,解决了联合类型问题。

【讨论】:

以上是关于Mongoose + TypeScript:有条件地在模型上找到()文档抛出错误:联合类型有签名,但没有一个相互兼容的主要内容,如果未能解决你的问题,请参考以下文章

Mongoose TypeScript ObjectId 转换 - 类型“字符串”不可分配给类型“条件<ObjectId |未定义>'

即使使用 `?` 链接或条件检查,Typescript Partial<T> 也会导致未定义的错误

TypeScript 中的 Mongoose 方法范围

Mongoose Typescript 2 Schema 有一个使用其他模式的字段

mongoose 和 typescript 如何自动将 '_id' 转换为 'id'?

用于TypeScript的Mongoose导入不起作用