DaMatt91
DaMatt91

Reputation: 726

Fetching Data from Nextjs13 Server Component

I am using NextJS and MongoDB (using Mongoose).

This is my Server Component:

import {
  getPosts
} from "@/lib/mongoDb/post";
import PostsClientComponent from "./PostsClientComponent";

const fetchPosts = async () => {
  let posts = await getPosts();
  return posts;
};


export default async function Page() {
  const posts = await fetchPosts();
 
  return (
    <PostsClientComponent
     posts={posts}
    />
  );
}

And this is my function getPosts()

export async function getPosts(){
  dbConnect()
  try 
    let posts = await Post.find();
    return posts
  }
  catch(err){
    console.log(err.message)
    return false;
  }
}

After running my webapp in dev I get a lot of warning messages: enter image description here

This error is driving me crazy!!

Upvotes: 1

Views: 1274

Answers (2)

Ermiyas Dagnachew
Ermiyas Dagnachew

Reputation: 1

Just stringify the JSON data and parse it before passing it to your client-side app.

Here's a possible fix

export default async function Page() {


const postsData = await fetchPosts();
const posts = JSON.parse(JSON.stringify(postData));
 
  return (
    <PostsClientComponent
     posts={posts}
    />
  );
}

Upvotes: 0

Arsalan Habib
Arsalan Habib

Reputation: 123

The problem is the data being returned by your find operation is not exactly what you expect.

The data returned by the find are not plain objects with just the properties defined in the schema, they are MongoDB Documents which have some extra properties and methods attached to them.

You can either convert them to JSON one by one by using the .toJSON() method, or by modifying your database query as follows to directly get the plain JSON objects.

export async function getPosts(){
  dbConnect()
  /* 
  By adding the lean method, we specify the db to 
  return plain json objects instead of MongoDB Documents.
  */
  try {
    let posts = await Post.find().lean();
    return posts
  }
  catch(err){
    console.log(err.message)
    return false;
  }
}

Upvotes: 1

Related Questions