我正在尝试记录对客户记录集合的更改。为了保持无懈可击,日志记录显然应该在 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/