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

在Firestore中使用Firebase Admin与TypeScript调用setDoc报错排查

问题分析与解决

直接错误原因

你在upsertInstance函数中使用了createHash方法,但没有导入Node.js的crypto模块。未导入时createHash为undefined,调用它就会抛出Error: expected a function错误。

修正代码

在upsert代码顶部添加crypto模块的导入,同时检查配置文件的导入路径是否正确:

import { createHash } from 'crypto';
import firestore from "../config/firebase"; // 注意:原代码导入路径写的firebaseAdmin,需和实际配置文件名一致

修正后的完整upsert函数(如果需要真正的upsert逻辑,需给set方法添加merge: true选项):

import { createHash } from 'crypto';
import firestore from "../config/firebase";

const upsertInstance = async (instance: Instance) => {
  const hashedUri = createHash('sha256').update(instance.uri).digest('hex')
  // 添加{ merge: true }实现存在则合并、不存在则创建的upsert逻辑
  const res = await firestore.doc(`instances/${hashedUri}`).set(instance, { merge: true });
  return res
}

额外注意事项

  • 导入路径校验:你的配置文件是config/firebase.ts,原导入代码写的../config/firebaseAdmin如果和实际文件名不匹配,会导致导入错误,请确保路径和文件名一致。
  • 敏感环境变量处理:Firebase Admin的私钥、服务邮箱等敏感信息,不应使用NEXT_PUBLIC_前缀(该前缀会将变量暴露给前端),应改用普通环境变量,且仅在服务器端代码中调用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 08:02:03