我面对这样一个事实,即功能上似乎相同的操作会导致不同的结果。
transaction.set(ref, data, {merge: true})
的情况下,仅从第二次执行操作获得结果,并且立即执行transaction.update(ref, data)
。
在两种情况下,所有环境和输入数据都相同。也许运行时有所不同?
异步updateFields(userId:字符串,storyId:字符串,allItemsSeen:布尔值,lastId ?:字符串|空):Promise {
await this.db.runTransaction(async (transaction) => {
const queryRef = this.refs.story(userId, storyId);
const query = await transaction.get(queryRef);
const data: any = {[ALL_ITEMS_SEEN]: allItemsSeen};
if (lastItemSeenId !== undefined) {
data[LAST_ITEM_SEEN_ID] = lastItemSeenId;
}
if (!query.empty) {
transaction.update(query.docs[0].ref, data); // is performed immediately.
==========================================
transaction.set(query.docs[0].ref, data, {merge: true}); // the result is obtained only from the second execution of the operation
}
});
}
update
调用仅在文档已经存在时对其进行更新。如果文档尚不存在,则update
调用将失败。
另一方面,set
调用将根据需要创建或更新文档。
此区别适用于事务和常规写入操作。