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

如何修复Firestore报错:FieldPath.documentId is not a function

问题:Firestore查询中FieldPath.documentId()调用失败

问题场景

需要从Firestore的两个集合拉取数据:Users集合的子集合MediaList存储用户影片列表,Media集合存储影片详情。目标是获取用户MediaList中的media_uid字段,以此匹配Media集合的对应数据。

已尝试操作

  • 确认已导入FieldPath:
import { getDocs, collection, getDoc, setDoc, addDoc, updateDoc, doc, where, query, writeBatch, FieldPath } from "firebase/firestore"
  • 验证所有media_uid均存在于Media集合中

报错代码行

const mediaQuery = query(mediaRef, where(FieldPath.documentId(), 'in', media_ids));

完整函数代码

export const getUserMedia = async (uid) => {
    try {
        const userDocRef = doc(db, 'Users', uid);
        const mediaListCollectionRef = collection(userDocRef, 'MediaList');
        const mediaListSnapshot = await getDocs(mediaListCollectionRef);
        const userData = mediaListSnapshot.docs.map((doc) => ({ ...doc.data(), key: doc.id }));

        // Get the document IDs directly from the MediaList collection
        const media_ids = mediaListSnapshot.docs.map((doc) => doc.id);
        console.log('media_ids:', media_ids);

        const mediaRef = collection(db, 'Media');

        // Use where-in query to fetch only documents with specified document IDs
        const mediaQuery = query(mediaRef, where(FieldPath.documentId(), 'in', media_ids));
        const mediaSnapshots = await getDocs(mediaQuery);
        console.log('mediaSnapshots:', mediaSnapshots.docs);

        const combinedData = mediaSnapshots.docs.map((docSnapshot, index) => {
            const mediaData = docSnapshot.exists() ? docSnapshot.data() : null;
            return mediaData ? { ...mediaData, ...userData[index] } : null;
        });

        console.log('combinedData:', combinedData);

        // return combinedData.filter((data) => data !== null);
    } catch (err) {
        console.error(err);
    }
};

报错信息

TypeError: firebase_firestore__WEBPACK_IMPORTED_MODULE_0__.FieldPath.documentId is not a function

解决方法

原因分析

该错误由Firebase JS SDK版本差异导致:在Firebase v9+模块化SDK中,FieldPath.documentId()已被移除,需直接导入独立的documentId函数使用。

修复步骤

  1. 更新导入语句,添加documentId:
import { getDocs, collection, getDoc, setDoc, addDoc, updateDoc, doc, where, query, writeBatch, FieldPath, documentId } from "firebase/firestore"
  1. 修改查询代码,用documentId()替换FieldPath.documentId():
const mediaQuery = query(mediaRef, where(documentId(), 'in', media_ids));

额外逻辑修正

根据你的需求描述,当前代码中media_ids取的是MediaList文档的ID,但你实际需要的是文档内的media_uid字段,需调整media_ids的获取方式:

const media_ids = mediaListSnapshot.docs.map((doc) => doc.data().media_uid);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 15:36:23