将 Mongodb 文档转换为 Typescript 接口

Seb*_*Fay 15 mongodb typescript

在我的 Typescript Express 应用程序中,我尝试从 mongoDB 检索文档,然后将该文档转换为接口定义的类型。

\n
const goerPostsCollection = databaseClient.client.db('bounce_dev1').collection('goerPosts');\nvar currentGoerPosts = await goerPostsCollection.findOne({ goerId: currentUserObjectId }) as GoerPosts;\nif (!currentGoerPosts) {\n    currentGoerPosts = CreateEmptyGoerPosts(currentUserObjectId);\n}\n
Run Code Online (Sandbox Code Playgroud)\n

接口定义如下

\n
export interface GoerPosts {\n    goerId: ObjectId;\n    numPosts: number;\n    posts: ObjectId[];\n};\n
Run Code Online (Sandbox Code Playgroud)\n

上面的代码一直对我有用,直到我将 typescript 从 4.4.4 更新到 4.5.2。现在代码不再有效,我收到错误消息:

\n
[ERROR] 03:30:48 \xe2\xa8\xaf Unable to compile TypeScript:\n[posts] src/routes/create-post.ts(37,28): error TS2352: Conversion of type 'WithId<Document> | null' to type 'GoerPosts' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.\n[posts]   Type 'WithId<Document>' is missing the following properties from type 'GoerPosts': goerId, numPosts, posts\n
Run Code Online (Sandbox Code Playgroud)\n

我可能可以恢复到 4.4.4,但我想知道是否有更好的方法可以干净利落地完成此操作。

\n

Var*_*orb 26

我也有这个问题。该toArray()函数返回一个WithId<Document>类型。您可以扩展此接口以使打字稿正常工作。

import type { WithId, Document } from 'mongodb'

interface GoerPosts extends WithId<Document> {
    goerId: ObjectId;
    numPosts: number;
    posts: ObjectId[];
}

var currentGoerPosts = (await goerPostsCollection.findOne({ goerId: currentUserObjectId }).toArray()) as GoerPosts;
Run Code Online (Sandbox Code Playgroud)

2022 年更新

您可以将类型传递给集合

export interface GoerPosts {
    goerId: ObjectId;
    numPosts: number;
    posts: ObjectId[];
};

const currentGoerPosts = databaseClient.client.db('bounce_dev1').collection<GoerPosts>('goerPosts').findOne({ goerId: currentUserObjectId });

Run Code Online (Sandbox Code Playgroud)

WithId<GoerPosts>无需扩展WithId接口即可返回

  • 如果您已将集合放入变量中,您也可以将类型传递给“find()”:“const posts = goersPostsCollection.find&lt;GoerPost&gt;({}).toArray()” (2认同)