You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从Mongo Atlas触发器向GCP PubSub发起认证请求?

解决MongoDB Atlas触发器向GCP Pub/Sub发送消息的createReadStream错误

问题背景

在MongoDB Atlas触发器中使用@google-cloud/pubsub库发送消息时,触发以下错误:

Error publishing message: FunctionError: TypeError: 'createReadStream' is not a function

错误核心原因:@google-cloud/pubsub的keyFilename参数期望接收本地文件路径,但Atlas环境无文件系统访问权限,且context.values.get("GOOGLE_APPLICATION_CREDENTIALS")返回的是GCP服务账号密钥的JSON内容而非路径,导致SDK尝试读取文件时失败。已有其他用户在MongoDB社区论坛遇到相同问题但未得到有效解决。

解决方案

直接将解析后的密钥JSON对象传入PubSub构造函数,替代keyFilename参数:

修改后的代码

exports = async function(changeEvent) {
  const {PubSub} = require("@google-cloud/pubsub");
  
  // 从Atlas Value Store获取密钥JSON并解析为对象
  const credsJson = context.values.get("GOOGLE_APPLICATION_CREDENTIALS");
  const credentials = JSON.parse(credsJson);
  
  const projectId = "<your-gcp-project-id>";
  const pubSubClient = new PubSub({
    projectId,
    credentials // 直接传入解析后的凭证对象
  });
  
  const topicName = "<your-pubsub-topic-name>";
  const topic = pubSubClient.topic(topicName);
  
  try {
    const data = "something";
    const dataBuffer = Buffer.from(data);
    const messageId = await topic.publish(dataBuffer);
    console.log(`Message ${messageId} published.`);
    return messageId;
  } catch(err) {
    console.error(`Error publishing message: ${err}`);
    throw err; // 抛出错误供Atlas触发器记录详情
  }
};

关键说明

  • 凭证传递方式:Atlas环境无法通过文件路径读取密钥,必须直接传入解析后的JSON对象
  • 异步处理:使用async/await替代Promise链式调用,简化代码并提升错误处理效率
  • Value Store配置:确保GOOGLE_APPLICATION_CREDENTIALS存储的是完整的GCP服务账号JSON字符串,无格式错误
  • 冗余依赖清理:如果未使用avro-js库,可直接移除以减少函数体积

内容的提问来源于stack exchange,提问作者Sylver11

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 01:24:55