This is the next.js code I am using to get a document from MongoDB using unique slug:
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)),
},
};
}
But it's giving me this error:
./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
My MongoDB data looks like this:
[
{
"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"
}
]
It's working if I hardcode my slug like this:
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)),
},
};
}
How can I pass slug dynamically to find the document I need?
CodePudding user response:
I don't know why I just deleted and recreated my database in MongoDB and it's now working with everything (Symbols, Different languages, Special characters) in the slug.