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

Angular项目Firestore同一集合批量写入异常及解决方案

问题原因与解决方案

问题原因

  • 你复用了同一个文档引用mail_doc_ref执行两次set操作。在Firestore批量写入逻辑中,针对同一文档的多次写入会以最后一次操作结果为准,第一次的set会被第二次完全覆盖,因此看起来第一次写入失效,且该操作属于合法逻辑,不会触发错误提示。

解决方案

要在同一集合中写入两个独立的文档,需要为每个邮件生成独立的文档引用,避免复用同一引用导致覆盖。修改后代码如下:

async sendMail() {
    console.log('sending mail');
    const mail_1 = this.mailing_service.createEmail(
      ['test@test.com'],
      'test',
      'test'
    );

    const mail_2 = this.mailing_service.createEmail(
      ['test@test.com'],
      'test',
      'test'
    );
    try {
      // 为每个邮件创建单独的文档引用
      const mailDocRef1 = doc(collection(this.firestore, 'email'));
      const mailDocRef2 = doc(collection(this.firestore, 'email'));

      const batch = writeBatch(this.firestore);
      batch.set(mailDocRef1, mail_1);
      batch.set(mailDocRef2, mail_2);

      await batch.commit();
      console.log('mail sent');
    } catch (error) {
      console.error(error);
    }
}

补充说明

如果你的需求是对同一文档做局部更新而非覆盖整个文档,可将set替换为update方法,但此场景下你需要存储两个独立邮件,因此必须使用不同的文档引用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 02:37:14