以下是我使用的next.js代码,用于使用唯一的插件从MongoDB获取文档:
export async function getStaticProps(context) {
const postSlug = context.params.postPage;
const { db } = await connectToDatabase();
const posts = await db
.collection("posts")
.find({ slug: { $eq: postSlug } })
.toArray();
return {
props: {
posts: JSON.parse(JSON.stringify(posts)),
},
};
}
但它给了我这样一个错误:
./node_modules/mongodb/lib/cmap/auth/gssapi.js:4:0
Module not found: Can't resolve 'dns'
Import trace for requested module:
./node_modules/mongodb/lib/index.js
./pages/[videoPage].js
https://nextjs.org/docs/messages/module-not-found
我的MongoDB数据如下所示:
[
{
"Post": "this is a post",
"_id": ObjectId("630f3c32c1a580642a9ff4a0"),
"slug": "this-is-a-title",
"title": "This is a title"
},
{
"Post": "this is a post",
"_id": ObjectId("630f3c32c1a580642a9ff4a1"),
"slug": "this-is-a-titleb",
"title": "This is a titleB"
}
]
如果我像这样硬编码我的slug,它就会起作用:
export async function getStaticProps() {
const { db } = await connectToDatabase();
const posts = await db
.collection("posts")
.find({ slug: { $eq: "this-is-a-titleb" } })
.toArray();
return {
props: {
posts: JSON.parse(JSON.stringify(posts)),
},
};
}
如何动态传递slug以找到我需要的文档?