firestore transaction.set(ref, data, {merge: true}) 和 transaction.update(ref, data) 有什么区别?
what difference between firestore transaction.set(ref, data, {merge: true}) and transaction.update(ref, data)?
我面临这样一个事实,即看似功能相同的操作会导致不同的结果。
在transaction.set(ref, data, {merge: true})
的情况下,只从第二次执行运算得到结果,transaction.update(ref, data)
立即执行。
两种情况下的所有环境和输入数据都相同。也许运行时间有所不同?
async updateFields(userId: string, storyId: string, allItemsSeen: boolean,
lastId?: string | null): Promise<void> {
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
调用将根据需要创建或更新文档。
同样的区别适用于事务和常规写入操作。
我面临这样一个事实,即看似功能相同的操作会导致不同的结果。
在transaction.set(ref, data, {merge: true})
的情况下,只从第二次执行运算得到结果,transaction.update(ref, data)
立即执行。
两种情况下的所有环境和输入数据都相同。也许运行时间有所不同?
async updateFields(userId: string, storyId: string, allItemsSeen: boolean,
lastId?: string | null): Promise<void> {
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
调用将根据需要创建或更新文档。
同样的区别适用于事务和常规写入操作。