javascript - 如何在事务中创建新的 Firestore 文档

标签 javascript firebase google-cloud-firestore transactions

我正在尝试记录对客户记录集合的更改。为了保持无懈可击,日志记录显然应该在 Firestore 事务中创建。我使用 transaction.set 来应用客户文档更改没有任何问题,但每次此类更改都需要在我的 transactionLogs 集合中创建新文档。在这里,事情变得严重错误日志文档由时间戳字段标识,当我运行以下代码时:...

import { initializeApp } from 'firebase/app';
import {
    getFirestore, collection, query, getDoc,
    getDocs, where, orderBy, addDoc, doc, updateDoc, deleteDoc, runTransaction
} from 'firebase/firestore';

var firebaseApp = initializeApp(firebaseConfig);
var db = getFirestore(firebaseApp);

// code to read and validate update to customer documents and to call the following asynch function

function performCustomerUpdate(parameters) {

await runTransaction(db, async (transaction) => {

 // update Customer document and build a transactionLog object

 const newLogRef = collection(db, 'transactionLogs', transactionLog.timeStamp);
 await transaction.set(newLogRef, transactionLog);

});
}

...transaction.set 指令失败,并显示类似“无效的集合引用。集合引用必须具有奇数个段,但 transactionsLogs/1645451217221 有 2 个。” 在这个特定实例中,1645451217221 将是 transactionLog.timesStamp 的值。

有人对这里发生的情况以及如何修复错误有建议吗?我的理解是,如果提供的引用不存在,transaction.set 将创建一个新记录,所以我应该在正确的行上。但为什么 Firestore 认为我想在名为 transactionsLogs/1645451217221 的集合中创建它?如何在名为“transactionsLogs”的集合中为由字符串“1645451217221”标识的文档创建引用?

最佳答案

如果您指定文档 ID(而不是使用自动生成的 ID),则必须使用 doc() 而不是 collection() 来创建 DocumentReference :

const newLogRef = doc(db, 'transactionLogs', transactionLog.timeStamp);

collection() 函数用于创建一个 CollectionReference

还结帐:Firestore: What's the pattern for adding new data in Web v9?


My understanding is that transaction.set will create a new record if the supplied reference doesn't exist

如果文档存在,它将覆盖现有文档。

关于javascript - 如何在事务中创建新的 Firestore 文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71210025/

相关文章:

javascript - JS图表旋钮: animate from value to value rather than 0

swift - 使用 firebase realtime 创建隐藏的用户节点

swift - 如何使用firebase确定数据是否已完成快速加载

javascript - 时间戳验证 Firestore

javascript - 如何确定选择已被清除

javascript - 使用 AJAX 在 elasticsearch 中查询动态聚合

Android-如何将 Firebase Uid 保存到 SharedPreferences?

Javascript:无法将对象数组存储到 Firestore

javascript - Drupal Theming js 错误 - 无法读取未定义的属性 'top'

python - Firestore .get() 导致超出截止日期