首页 > 解决方案 > 如何在 NodeJS 项目中使用 Google Cloud FireStore 模拟器?

问题描述

我正在尝试使用此工具来测试我的 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.jsgoogle-cloud-platformgoogle-cloud-firestore

解决方案


您需要在单独的终端中设置和启动模拟器

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

您也可以在此处查看此示例


推荐阅读