以下是我使用的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以找到我需要的文档?

推荐答案

我不知道为什么我刚刚在MongoDB中删除并重新创建了我的数据库,现在它可以处理插件中的所有内容(符号、不同语言、特殊字符).

Javascript相关问答推荐

导入图像与内联包含它们NextJS

功能和普通对象之间的原型污染

如何避免使用ajax在Vue 3合成API中重定向

强制执行useStatego struct 化变量[foo,setFoo]的命名约定?

如何提取Cypress中文本

当在select中 Select 选项时,我必须禁用不匹配的 Select

网页自检测外部元素无法加载

Snowflake JavaScript存储过程返回成功,尽管预期失败

Regex结果包含额外的match/group,只带一个返回

在open shadow—root中匹配时,使用jQuery删除一个封闭的div类

我可以使用使用node.js创建的本地主机来存储我网站上提交的所有数据吗?没有SQL或任何数据库.只有HTML语言

使用Google API无法进行Web抓取

在运行时使用Next JS App Router在服务器组件中运行自定义函数

第二次更新文本输入字段后,Reaction崩溃

如何在不影响隐式类型的情况下将类型分配给对象?

类构造函数忽略Reaction Native中的可选字段,但在浏览器中按预期工作

如何将zoom 变换应用到我的d3力有向图?

AJAX POST在控制器中返回空(ASP.NET MVC)

如果没有页面重新加载Angular ,innerHTML属性绑定不会更新

按什么顺序接收`storage`事件?