我正在制作一个网页,该网页从 mongoDB(atlas BASIC 免费计划)中获取数据,并具有带有 SSG 的动态路由页面。动态路由页面,[cogid].js,有 getstaticpaths 和 getstaticprops。getstaticpaths 似乎有效,但 getstaticprops 无效。我猜问题是getstaticprops中的变量“params.cogid”......
import { MongoClient } from "mongodb";
const { MONGODB_URI, MONGODB_DB } = process.env;
export default function Cog({ cogData }) {
return (
<div className="container mx-auto px-2 my-5 flex flex-col ">
<p>COG ID: COG{cogData.cog_id}</p>
<p>name: {cogData.name}</p>
</div>
);
}
export async function getStaticPaths() {
const client = new MongoClient(MONGODB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
if (!client.isConnected()) await client.connect();
const res = await client
.db(MONGODB_DB)
.collection("test1")
.find({})
.project({ cog_id: 1, _id: 0 })
.toArray();
if (client.isConnected()) client.close();
const paths = res.map((copiedCog) => ({
params: { cogid: copiedCog.cog_id },
}));
return { paths, fallback: false };
}
export async function getStaticProps({ params }) {
const client = new MongoClient(MONGODB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
if (!client.isConnected()) await client.connect();
const resp = await client
.db(MONGODB_DB)
.collection("test1")
.findOne({ cog_id: params.cogid });
if (client.isConnected()) client.close();
const cogData = await JSON.parse(JSON.stringify(resp));
return { props: { cogData } };
}