为了保证原子性需要使用事务来修改两个 collection。我现在的需求是,要修改某个 collection 中的多条数据,和另一个 collection 中的一条数据。事务不支持 where,每次只能修改一条数据。所以只能使用遍历修改数据库。这样就会出现下面的错误提示
Error: document.update:fail -501001 resource system error. [ResourceUnavailable.TransactionBusy] Transaction is busy. Please check your request, but if the problem persists, contact us.
目前遍历操作 10 次数据库就会出现上面的提示。
const updateStudentPromises = filteredStudents.data.map(student => {
const courseIndex = student.courses.findIndex(course => course._id === courseId);
return transaction.collection('students')
.doc(student._id)
.update({
data: {
records: _.push({
name,
time: new Date(time),
address,
scheduleId,
createdAt: new Date(),
}),
[`courses.${courseIndex}.remain`]: _.inc(-1),
}
});
});
// 等待所有更新操作完成
const studentResult = await Promise.all(updateStudentPromises);
如何解决上面的问题?修改数据库结构?还是不使用事务就能达到想要的效果?