简体   繁体   中英

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

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM