【问题标题】:How to use Google Cloud FireStore emulator with NodeJS project?如何在 NodeJS 项目中使用 Google Cloud FireStore 模拟器?
【发布时间】:2020-06-18 07:21:39
【问题描述】:

我正在尝试使用这个工具来测试我的 NodeJS 应用程序:

https://cloud.google.com/sdk/gcloud/reference/beta/emulators/firestore

当我尝试向 firestore 数据库添加内容时,我收到此错误:

Error: Unable to detect a Project Id in the current environment.

我认为这很正常,因为本地没有GCP项目。

我想我必须配置firestore:

const Firestore = require('@google-cloud/firestore');

const db = new Firestore({
  projectId: 'YOUR_PROJECT_ID',
  keyFilename: '/path/to/keyfile.json',
});

使用 Google Cloud Firestore 模拟器时,如何创建“虚拟”项目 ID? 另外,密钥文件是强制性的吗?

如果存在“FIRESTORE_EMULATOR_HOST”环境变量,则最终目标是使用本地模拟器进行 firestore。

【问题讨论】:

    标签: node.js google-cloud-platform google-cloud-firestore


    【解决方案1】:

    您需要在单独的终端中设置和start the emulator

    gcloud beta emulators firestore start
    

    然后对于项目 ID,您可以按照文档和 github 说明进行操作:

    firebase serve --only firestore
    

    然后

    require "google/cloud/firestore"
    
    # Make Firestore use the emulator
    ENV["FIRESTORE_EMULATOR_HOST"] = "127.0.0.1:8080"
    
    firestore = Google::Cloud::Firestore.new project_id: "emulator-project-id"
    
    # Get a document reference
    nyc_ref = firestore.doc "cities/NYC"
    
    nyc_ref.set({ name: "New York City" }) # Document created
    

    您也可以查看this example here

    【讨论】:

    • 谢谢。我找到了同样的例子!一个小技巧是使用 --host-port:127.0.0.1:8686 (例如端口值),因为 nodeJS 客户端不接受默认的 ipv6 ::1:8686 表示法:)
    • 对于 nodeJs 它看起来更像:const firestore = new Firestore({ projectId: "emulator-project-id", host: "127.0.0.1:8686", credentials: "", ssl: false, keyFilename: '' });
    【解决方案2】:

    你需要使用express.js框架和node js向@google-cloud/firestore发出请求,最佳实践是从https://cloud.google.com/nodejs/getting-started?hl=fa开始

    【讨论】:

    • 谢谢,但我使用 express.js 和所有这些好东西,但现在我的问题是我尝试在我的计算机上使用 Google Cloud Firestore 模拟器在 GCP 之外进行开发。对此工具有何反馈?
    • @google-cloud/firestore 是一个库,不能向它发出请求。此外,使用此客户端不需要 express.js,只有 Node 是。
    猜你喜欢
    • 2021-07-19
    • 2019-07-18
    • 1970-01-01
    • 2019-11-13
    • 2021-02-11
    • 1970-01-01
    • 2021-05-16
    • 2019-03-14
    • 1970-01-01
    相关资源
    最近更新 更多