1

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!!

DaMatt91
  • 544
  • 1
  • 7
  • 18
  • The data you are receiving from your mongo db instance seems to include a function or something of sorts. You can only pass objects from server to client components. As per my research (googling your error message) there is an open [issue](https://github.com/vercel/next.js/issues/47447) related to this as well. – Fabio Nettis Jun 22 '23 at 14:47

1 Answers1

1

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;
  }
}