My MongoDB Data looks like this
{
"_id": {
"$oid": "630f3c32c1a580642a9ff4a0"
},
"title": "this is a title",
"paragraph": "this is a paragraph"
}
My pages folder looks like this
[posts].js
_app.js
index.js
Inside index.js I used getStaticProps() to get data from MongoDB Then from next.js link component I made a new URLs for [posts].js using MongoDB _Id
<div>
{data.map((myData) => (
<h2>
<Link href={`/${encodeURIComponent(myData._id)}`}>
<a>{myData._id}</a>
</Link>
</h2>
))}
</div>
Inside [posts].js getStaticPaths() method I used same MongoDB _Id to fetch all paths like this
const paths = data.map((myData) => {
return {
params: {
postPage: data._id.toString(),
}
}
})
return {
paths,
fallback: false,
}
Then inside the same [post].js I used getStaticProps(context) to get that MongoDB _Id and get data about that one document only by its _Id like this
const postId = context.params.postPage;
const { db } = await connectToDatabase();
const posts = await db
.collection("posts")
.find({"_id": new ObjectID(`${postId}`)})
.toArray();
And it's working fine, but I want the title to be my URL for SEO and also want to find the document by its _Id.
how can I do that?