简体   繁体   English

使用 MongoDB 在 Next.js 中创建帖子页面及其 URL 的最佳方法?

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

My MongoDB Data looks like this我的 MongoDB 数据看起来像这样

{
  "_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在 index.js 中,我使用getStaticProps()从 MongoDB 获取数据然后从 next.js 链接组件我使用 MongoDB 为 [posts].js 创建了一个新 URL

<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在 [posts].js getStaticPaths()方法中,我使用相同的 MongoDB _Id 来获取所有这样的路径

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然后在同一个 [post].js 中,我使用 getStaticProps(context) 获取 MongoDB _Id 并仅通过其 _Id 获取有关该文档的数据,如下所示

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.它工作正常,但我希望标题是我的 URL 用于 SEO,并且还想通过它的 _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.如果您的标题字段是唯一的,那么您可以在数据库中搜索它而不是 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)如果它不是唯一的,那么您可以根据唯一的标题生成一个 slug(任何可以生成更好的唯一字符串的方式)

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.您可以在 URL 中有两个变量,第一个是 id,第二个是标题,然后通过 id 获取并验证标题。 (similar to how this page seems to work!) (类似于此页面的工作方式!)

You can use state import { useState } from 'react';您可以使用 state import { useState } from 'react'; to store _id of document and pass it in [posts].js to get data about that one document.存储文档的 _id 并将其传递到 [posts].js 以获取有关该文档的数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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