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
相关产品推荐
相关产品推荐

