我正在try 创建一个事务,以便每次添加文档时,都会根据最新的计数更新计数.这似乎是两个世界中最好的,使用increment
和getCountFromServer
,这样您只需按写入收费,而不必处理increment
的痛苦和不一致.
这是一个添加新的待办事项,同时增加用户的待办事项计数的示例.
FireBase JS SDK
问题似乎是,getCountFromServer
会回报一个promise
const userRef = doc(db, `users/${uid}`);
const todoRef = doc(collection(db, 'todos'));
const todoQuery = query(
collection(db, 'todos'),
where('uid', '==', uid)
);
await runTransaction(db, async (transaction) => {
// Should be in transaction
const todoCountDoc = await getCountFromServer(todoQuery);
transaction.update(userRef, {
todoCount: todoCountDoc.data().count + 1
});
transaction.set(todoRef, {
uid,
text,
complete: false,
created: serverTimestamp()
});
});
我需要做的是将以下内容放入交易中:
const todoCountDoc = await getCountFromServer(todoQuery);
类似于:
// DOES NOT WORK
const todoCountDoc = await transaction.get(getCountFromServer(todoQuery));
我有一种感觉,这不是安全原因这不起作用,只是它没有在JS SDK中实现,因为没有人考虑过它.话又说回来,为什么create
不是选项,而set
是🤷🏼.我是不是遗漏了什么?
node JS
这在 node JS中似乎工作得很好,但我想在前端这样做:
const userRef = db.doc(`users/${uid}`);
const todoRef = db.collection('todos').doc();
const currentCount = db
.collection('todos')
.where('uid', '==', uid)
.count();
db.runTransaction(async (transaction) => {
const todoCountDoc = await transaction.get(currentCount);
transaction.update(userRef, {
todoCount: todoCountDoc.data().count + 1
});
transaction.create(todoRef, {
uid,
text,
complete: false,
created: FieldValue.serverTimestamp()
});
});
我怎么才能在前台做到这一点?
J