? Google Cloud Functions ?????? MongoDB Atlas ??

Posted

技术标签:

【中文标题】从 Google Cloud Functions 控制台中访问 MongoDB Atlas 集群【英文标题】:Accessing a MongoDB Atlas Cluster from within Google Cloud Functions Console 【发布时间】:2018-07-29 06:24:46 【问题描述】:

我正在编写一个基本的谷歌云函数,它将从 MongoDB Atlas 查询一个 MongoDB 集群。我在 Google 控制台中编写,并且确定将 "mongodb": "^3.0.2" 添加到 package.json 文件中的依赖项中。

功能如下(为了安全起见,我在uri中替换了有效密码等):

/**
* Responds to any HTTP request that can provide a "message" field in the 
body.
 *
 * @param !Object req Cloud Function request context.
 * @param !Object res Cloud Function response context.
 */
exports.myPackage = (req, res) =>     
  var MongoClient = require('mongodb').MongoClient;
  var uri = "mongodb+srv://<USERNAME>:<PASSWORD>@<CLUSTER-NAME>-vtbhs.mongodb.net/test";
  MongoClient.connect(uri, function(err, client) 
    if (err) 
      console.log('err');
      console.log(err);
     else 
      const collection = client.db("test").collection("devices");
    
  );

  res.status(200).send('Success');

我确定驱动程序是最新的,并且我直接从 Atlas 文档复制了大部分代码。我已将 Atlas 的所有 IP 列入白名单以进行测试。

每次函数运行时,连接回调中都会出现以下错误:

" Error: querySrv ESERVFAIL _mongodb._tcp.<CLUSTER-NAME>-vtbhs.mongodb.net
at errnoException (dns.js:28:10)
at QueryReqWrap.onresolve [as oncomplete] (dns.js:219:19)
code: 'ESERVFAIL',
errno: 'ESERVFAIL',
syscall: 'querySrv',
hostname: '_mongodb._tcp.<CLUSTER-NAME>-vtbhs.mongodb.net' "

我之前也遇到过类似的错误:

URI does not have hostname, domain name and tld at module.exports

虽然自从我在 Mongo 中调整了我的密码后,它似乎不再弹出(其中可能有一个非 html 编码的字符)。

提前感谢您的帮助!

【问题讨论】:

最初的错误URI does not have hostname, domain name and tld at module.exports 是因为我的密码中有一个非转义的@ 符号。更多详情请见this SO post 检查this similar -but with mysql- post。我现在想不出解决方案,也许你可以。如果有,请分享... 【参考方案1】:

我遇到了完全相同的问题。运行 firebase deploy 后,MongoDB Atlas 和 mLab 连接均失败,但使用 firebase serve 在本地工作。

我认为有两个问题:

    免费 Spark 计划禁用出站网络。您必须升级到 Blaze 计划(即用即付)才能做到这一点。我刚换了层,现在可以了。

Spark 计划仅允许向 Google 拥有的出站网络请求 服务。配额内允许入站调用请求。在 在 Blaze 计划中,Cloud Functions 提供永久免费层。这 前 2,000,000 次调用、400,000 GB-sec、200,000 CPU-sec 和 5 GB 每月免费提供互联网出口流量。你是 仅对超过此免费配额的使用收费。定价基于 调用总数和计算时间。计算时间为 根据为 功能。使用限制也通过每天和 100 秒执行 配额。如需了解更多信息,请参阅云函数定价。

https://firebase.google.com/pricing/

您必须提供信用卡,但只要您保持在他们的数据配额内,您显然不会被收费。我会试试看效果如何。

    升级后,您的 MongoDB Atlas 连接可能仍然失败(而 mLab 字符串可以工作)。这是因为您的查询 URI 使用的是 Mongo 3.6 SRV 地址,而不是 Mongo 3.4 驱动程序的“mongodb://”协议。尝试切换驱动程序版本,看看它是否有效。

【讨论】:

【参考方案2】:

在 Mongo Atlas 面板的白名单中设置“0.0.0.0/0”。

【讨论】:

请在您的答案中添加一些解释,以便其他人学习

以上是关于? Google Cloud Functions ?????? MongoDB Atlas ??的主要内容,如果未能解决你的问题,请参考以下文章