【问题标题】:Stuck trying to fetch data from MongoDB into Gatsby using `gatsby-source-mongodb`尝试使用 `gatsby-source-mongodb` 从 MongoDB 获取数据到 Gatsby
【发布时间】:2019-06-03 00:54:56
【问题描述】:

因此似乎几乎没有关于如何执行此操作的详细文档。基本上我必须指导我的是this。我已经跟进了映射媒体类型功能,此时我已经陷入困境。它举了一个例子:从集合中获取数据以使用降价。但这不是我想要达到的目标。

基本上我想要做的是从 Mongo 导入几个集合,我打算将它们拉入我的 Gatsby 应用程序 - 可能使用 GraphQL。

到目前为止,这就是我对 gatsby-config.js 所做的事情:

    {
      resolve: `gatsby-source-mongodb`,
      options: {
        dbName: `REDACTED`,
        collection: `articles`,
        map: { articles: { /* WHAT DO I DO HERE? */ } }
      },
      server: { address: `REDACTED`, port: 43532 },
      auth: { user: `REDACTED`, password: `REDACTED` },
      extraParams: { replicaSet: `test-shard-0`, ssl: true, authSource: `admin` }
    }

在此之后,我需要找到一种查询导入集合的方法,我不知道该怎么做。

非常感谢您提供的任何帮助!

【问题讨论】:

    标签: javascript reactjs mongodb graphql-js gatsby


    【解决方案1】:

    首先,我的问题中的一个主要错误是我将serverauthextraParams 放在options 对象之外。

    以下配置使我能够让 Atlas 正常工作:

    {
        resolve: `gatsby-source-mongodb`,
        options: {
            dbName: `your-database-name`,
            collection: [`yourCollection1`, `yourCollection2`],
            server: { address: 'cluster0-shard-00-01-XXXX.mongodb.net', port: 27017},
            auth: { user: 'yourUserName', password: 'yourPassword' },
            extraParams: { replicaSet: 'Cluster0-shard-0', ssl: true, authSource: `admin`, retryWrites: true }
        }      
    }
    

    注意:replicaSet 参数必须与您的地址的开头匹配(如示例所示)。您还可以通过单击 cloud.mongodb.com 上集群主信息面板上的 CONNECT 按钮找到您的集群 URL。 (下图)

    【讨论】:

      【解决方案2】:

      文档看起来很清楚。

      基本上我想做的是从 Mongo 导入几个集合,

      // In your gatsby-config.js
      module.exports = {
        plugins: [
          {
            resolve: `gatsby-source-mongodb`,
            options: { dbName: `local`, collection: [`documents`, `vehicles`] },
          },
        ],
      }
      

      在此之后,我需要找到一种查询导入集合的方法

      query {
        allMongodbLocalDocuments {
          edges {
            node {
              id
              url
              name
            }
          }
        }
      }
      

      注意:根据您的dbName,查询allMongodbLocalDocuments 可能会因您的情况而有所不同。但是您应该能够在 GraphiQL (http://localhost:8000/___graphql) 中找到可用的查询

      现在您应该可以在 GraphiQL 中测试上述查询了。

      然后,看看 gatsby using mongodb example 项目。在gatsby-node.js 中,他们使用上述查询从./src/templates/item.js 的模板中为查询中的每个节点创建一个页面

      【讨论】:

      • 你能在 GraphiQL 中测试查询吗?
      • 感谢您的回复 :) 我不得不找一个朋友来帮助我。基本上我在配置文件中错误地设置了插件。如您所见,我将 server、auth、extraParams 放在选项之外。我现在已经可以使用 GraphiQL 了。我的朋友将很快发布详细的答案,以准确解释需要在配置文件中添加什么才能连接到 MongoDB Atlas。
      • @JossClassey 你能展示你的解决方案吗,因为我还没有得到它的工作。
      猜你喜欢
      • 2019-12-10
      • 1970-01-01
      • 2020-03-20
      • 2021-08-27
      • 2023-02-10
      • 2021-12-16
      • 2021-07-01
      • 2020-03-21
      • 2020-11-07
      相关资源
      最近更新 更多