Seb*_*Fay 15 mongodb typescript
在我的 Typescript Express 应用程序中,我尝试从 mongoDB 检索文档,然后将该文档转换为接口定义的类型。
\nconst goerPostsCollection = databaseClient.client.db('bounce_dev1').collection('goerPosts');\nvar currentGoerPosts = await goerPostsCollection.findOne({ goerId: currentUserObjectId }) as GoerPosts;\nif (!currentGoerPosts) {\n currentGoerPosts = CreateEmptyGoerPosts(currentUserObjectId);\n}\nRun Code Online (Sandbox Code Playgroud)\n接口定义如下
\nexport interface GoerPosts {\n goerId: ObjectId;\n numPosts: number;\n posts: ObjectId[];\n};\nRun 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\nRun Code Online (Sandbox Code Playgroud)\n我可能可以恢复到 4.4.4,但我想知道是否有更好的方法可以干净利落地完成此操作。
\nVar*_*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)
您可以将类型传递给集合
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接口即可返回
| 归档时间: |
|
| 查看次数: |
8838 次 |
| 最近记录: |