小编Seb*_*Fay的帖子

将 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 …
Run Code Online (Sandbox Code Playgroud)

mongodb typescript

15
推荐指数
1
解决办法
8838
查看次数

标签 统计

mongodb ×1

typescript ×1