[英]Building a dashboard in Next.js : best practices to make pages private with roles, without "flickering", using JWT authentication?
[英]Best way Make Posts Pages and their URLs in Next.js with MongoDB?
我的 MongoDB 数据看起来像这样
{
"_id": {
"$oid": "630f3c32c1a580642a9ff4a0"
},
"title": "this is a title",
"paragraph": "this is a paragraph"
}
我的页面文件夹看起来像这样
[posts].js
_app.js
index.js
在 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>
在 [posts].js getStaticPaths()
方法中,我使用相同的 MongoDB _Id 来获取所有这样的路径
const paths = data.map((myData) => {
return {
params: {
postPage: data._id.toString(),
}
}
})
return {
paths,
fallback: false,
}
然后在同一个 [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();
它工作正常,但我希望标题是我的 URL 用于 SEO,并且还想通过它的 _Id 找到文档。
我怎样才能做到这一点?
如果您的标题字段是唯一的,那么您可以在数据库中搜索它而不是 id。
如果它不是唯一的,那么您可以根据唯一的标题生成一个 slug(任何可以生成更好的唯一字符串的方式)
您可以在 URL 中有两个变量,第一个是 id,第二个是标题,然后通过 id 获取并验证标题。 (类似于此页面的工作方式!)
您可以使用 state import { useState } from 'react';
存储文档的 _id 并将其传递到 [posts].js 以获取有关该文档的数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.