【发布时间】:2021-01-11 20:39:15
【问题描述】:
我正在使用 Next.js,我正在尝试使用 TypeScript 和 mongoose 查询 MongoDB,但我遇到了类型错误。
types.d.ts
type dbPost = {
_id: string
user: {
uid: string
name: string
avatar: string
}
post: {
title: string
description: string
markdown: string
slug: string
createdAt: string
}
}
export const getSlugData = async (slug: string) => {
await dbConnect()
const data:
| Pick<dbPost, '_id' | 'post' | 'user'>
// The problem seems to be here with Pick[]
| Pick<dbPost, '_id' | 'post' | 'user'>[]
| null = await Post.findOne({ 'post.slug': slug }).lean().select('-__v')
const post = {
...data,
_id: `${data._id}`,
// _id and createdAt are objects created by mongoose which can't be serialized.
// They must be converted to a string
post: {
...data.post,
createdAt: `${data.post.createdAt}`,
},
}
return post
}
我收到以下错误:
Property '_id' does not exist on type 'Pick<dbPost, "_id" | "post" | "user"> | Pick<dbPost, "_id" | "post" | "user">[]'.
Property '_id' does not exist on type 'Pick<dbPost, "_id" | "post" | "user">[]'.ts(2339)
Pick<>[] 我做错了什么?
package.json
"dependencies": {
"mongoose": "^5.10.6",
...
},
"devDependencies": {
"@types/mongoose": "^5.7.36",
...
}
dbConnect() 是我从 Next.js 示例中获取的函数
【问题讨论】:
标签: mongodb typescript mongoose next.js