Home > Blockchain >  Best way Make Posts Pages and their URLs in Next.js with MongoDB?
Best way Make Posts Pages and their URLs in Next.js with MongoDB?

Time:09-08

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 use getStaticProps() to get data from MongoDB Then from next.js link component I make a new URL 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 use 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 use 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?

CodePudding user response:

If your title field is unique then you can just search that in the database instead of the id.

If it isn't unique then you could generate a slug based on the title which is unique (any way that would generate a nicer string that is unique)

You could have two variables in the URL, the first being the id, then the second be the title, and then just fetch via the id and validate the title. (similar to how this page seems to work!)

CodePudding user response:

You can use state import { useState } from 'react'; to store _id of document and pass it in [posts].js to get data about that one document.

  • Related