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

React中Firestore事务写入时如何使用merge选项?

Firestore事务中使用merge选项的实现方法

在Firestore的transaction.set()方法中,第三个参数接受一个配置对象,你只需要传入{ merge: true }就能启用merge功能——这样执行写入时,只会更新你指定的字段,不会覆盖文档中已有的其他数据。

修改后的完整代码如下:

import { runTransaction, doc } from "firebase/firestore";

try {
  await runTransaction(db, async (transaction) => {
    transaction.set(
      doc(db, 'users', auth.currentUser.uid),
      { referenceNo: "1RIK93029JDH8JU" },
      { merge: true }
    );
  });
} catch (e) {
  console.log("Transaction failed: ", e);
}

如果需要更精准地控制只合并特定字段,可以使用mergeFields选项,传入需要合并的字段数组,示例如下:

transaction.set(
  doc(db, 'users', auth.currentUser.uid),
  { referenceNo: "1RIK93029JDH8JU", otherField: "value" },
  { mergeFields: ["referenceNo"] } // 仅合并referenceNo字段
);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 16:16:07