You need to enable JavaScript to run this app. React Native使用Firestore删除文档内数组对象失败如何解决?
优惠活动
大模型
产品
解决方案
定价
更多

React Native使用Firestore删除文档内数组对象失败如何解决?

报错根因

你遇到的类型错误由代码语法结构错误直接导致:

  • firebase.firestore.FieldValue.arrayRemove(obj) 是Firebase提供的数组操作标记方法,返回值是字段操作标识而非Promise,你错误地将.then()/.catch()链式调用挂载在了这个方法后
  • 实际返回Promise、需要挂载异步回调的是update()方法,括号配对错误导致调用链完全错位
修复后的正确代码
const obj = product;
const user_post = await this.checkOwnerPost();

console.log(obj);

if (user_post){
  try {
    await this.firestore
      .collection('testCollection')
      .doc(user_post.doc_id)
      .update({
        products: firebase.firestore.FieldValue.arrayRemove(obj)
      });
    console.log("Document successfully updated!");
    return true;
  } catch (error) {
    console.log(error);
    return false;
  }
}

注:使用arrayRemove删除数组对象时,要求传入的对象和Firestore中存储的对象所有键值对完全匹配,不能有多余字段、也不能缺字段,否则会匹配失败无法删除

备选实现方案(手动操作数组,兼容性更高)

如果担心对象匹配不准确,可以先拉取文档、手动过滤数组后再更新,实现效果一致:

if (user_post){
  try {
    // 先拉取当前文档数据
    const docRef = this.firestore.collection('testCollection').doc(user_post.doc_id);
    const docSnap = await docRef.get();
    const currentProducts = docSnap.data().products || [];
    // 过滤掉要删除的对象,这里用唯一标识key匹配,可根据实际业务调整匹配规则
    const updatedProducts = currentProducts.filter(item => item.key !== obj.key);
    // 写回新数组
    await docRef.update({ products: updatedProducts });
    console.log("Document successfully updated!");
    return true;
  } catch (error) {
    console.log(error);
    return false;
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 10:45:03