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

Firestore用户引用字段被设为字符串而非引用类型问题

问题解决:将Firestore文档中的用户字段改为引用类型

问题描述

创建新用户时,Cloud Functions会自动在WorkoutCycles集合创建文档,但其中user字段存储的是用户UID字符串,而非Firestore的文档引用类型。

解决方案

要存储文档引用,不能直接使用用户UID字符串,需要通过Firebase Admin SDK创建对应的文档引用对象。修改代码中userDocReference的定义,并在set()方法中使用该引用对象即可。

修改后的代码

import functions = require("firebase-functions");
import admin = require("firebase-admin");

admin.initializeApp();

"use strict";

exports.createWorkoutCycle = functions.firestore
    .document("users/{userId}")
    .onCreate((snap, context) => {
      // 使用Firestore原生Timestamp替代字符串日期,更适合数据库操作
      const createTimestamp = admin.firestore.Timestamp.now();
      // 创建用户文档的引用对象,而非仅存储UID字符串
      const userDocReference = admin.firestore().doc(`users/${snap.id}`);
      return admin.firestore().collection("WorkoutCycles").doc().set({
        name: "New Workout Cycle",
        createTimestamp: createTimestamp,
        user: userDocReference,
      });
    });

关键说明

  • snap.id仅返回用户文档的UID字符串,而Firestore的引用类型是包含完整文档路径信息的对象,必须通过admin.firestore().doc(文档路径)生成。
  • 额外优化:将字符串格式的日期替换为Firestore原生Timestamp类型,后续进行时间排序、范围查询等操作时会更便捷。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 17:39:54