添加新用户后,如何获取users
集合中所有记录的记录(几乎执行对帐)?我注意到有时用户计数可能不同步。因此,在用户增加1之后,我想检查计数器是否与用户数相同。这可能吗?
exports.createUser = functions.firestore
.document('users/{userId}').onCreate(() => {
const ref = admin.firestore().collection('counters').doc('users');
return admin.firestore().runTransaction(async (transaction: any) => {
const doc = await transaction.get(ref);
if (!doc.exists) {
transaction.set(ref, { counter: 1 });
return 1;
}
const newCount = doc.data().counter + 1;
transaction.update(ref, {
counter: newCount,
});
return newCount;
})
.then((newCount: any) => {
console.log(
`Transaction successfully committed and new user count is '${newCount}'.`
);
})
.catch((error: any) => {
console.log('Transaction failed: ', error);
});
});