I'm working on a project using Next.js and attempting to query MongoDB with TypeScript and mongoose, but I keep encountering a type error.
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 issue seems to be arising 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 that can't be serialized.
// They need to be converted to strings
post: {
...data.post,
createdAt: `${data.post.createdAt}`,
},
}
return post
}
I'm encountering the following error:
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)
What am I doing wrong with Pick<>[]
?
package.json
"dependencies": {
"mongoose": "^5.10.6",
...
},
"devDependencies": {
"@types/mongoose": "^5.7.36",
...
}
dbConnect() is a function taken from the Next.js examples