I’m writing a blog with Next.js and mongoDB with mongoose to learn CRUD with the stack. When I log the return from the Post.find() in the backend everything looks fine and is working as expected. But when it goes to the frontend in a next response it is undefined. my guess is I am applying JSON.stringify wrong or I am messing up with asynchrony somewhere (I’m also newish to Next but know React). Here is my backend code:
export async function GET(request: Request){
try {
await dbConnect()
if (request.url === `${process.env.API_URL}/api/posts`){
const posts = await Post.find({})
return new NextResponse(JSON.stringify(posts), {status: 201})
}else{
const url = new URL(request.url)
const searchParams = new URLSearchParams(url.searchParams)
const posts = await Post.find({
slug: {
$eq: `${searchParams.get('slug')}`
},
})
return new NextResponse(JSON.stringify(posts), {status: 201})
}
} catch (error: any) {
return NextResponse.json(error.message)
}
}
and my frontend fetch function is this:
//fetch posts from mongodb
async function fetchPosts(){
const res = await fetch(`${process.env.API_URL}/api/posts`)
const posts = await res.json()
console.log(posts)
return (posts)
}
if it’s relevant the frontend is SSR