正如 Node.js 客户端库 update() 方法的文档中所述,它返回一个 Transaction,它“用于链接方法调用”。 (请注意,Admin SDK 的 update() 方法的行为方式完全相同)。
因此,例如,如果在事务中您想从课堂文档中获取一个值,请增加它并使用它来更新来自两个不同集合(classrooms 和 students)的两个文档,您可以这样做如下:
const db = firebase.firestore(); //or admin.firestore() in a Cloud Function
const docRef1 = db.collection('classrooms').doc('classroomDocId');
const docRef2 = db.collection('students').doc('studentDocId');
let transaction = db.runTransaction(t => {
let newNumericValue;
return t.get(docRef1 )
.then(doc => {
newNumericValue = doc.data().numericValue + 1; //You calculate the new value
return t.update(docRef1 , {numericValue : newNumericValue});
}).then(t => {
return t.update(docRef2 , {numericValue : newNumericValue});
});
}).then(result => {
console.log('Transaction success!' + result);
}).catch(err => {
console.log('Transaction failure:', err);
});
请注意,如果您需要在多次更新之前进行多次读取,“使用事务时,读取操作必须在写入操作之前进行。”
另一方面,如果您只想更新多个文档没有阅读一个或多个值(您在问题中说您“想要更新 branch.在课堂和学生集合中一次性命名“),您不需要使用事务。只需使用batched write,如下:
let batch = db.batch();
let cRef = db.collection('classrooms').doc('classroomDocId');
batch.set(cRef, {branch.name: 'newName'});
let sRef = db.collection('students').doc('studentDocId');
batch.update(sRef, {branch.name: 'newName'});
return batch.commit().then(function () {
// ...
});
更新您的 cmets
在您的 Cloud Function 中,您可以很好地链接不同的 Firestore 查询(使用 where()),并在每个 then() 中填充批处理,然后在最后一个 then() 中提交批处理。请参阅下面的示例(只需适应正确的查询):
let batch = admin.firestore().batch();
return admin.firestore().collection('students').where('branch.id', '==', documentId).get()
.then((querySnapshot) => {
querySnapshot.forEach((doc) => {
batch.update(doc.ref, {branch: {id: documentId, name: after.name}});
});
return admin.firestore().collection('student_public').where('branch.id', '==', documentId).get();
})
.then((querySnapshot) => {
querySnapshot.forEach((doc) => {
batch.update(doc.ref, {branch: {id: documentId, name: after.name}});
});
return batch.commit()
})
.catch(err => { console.log('error===>', err); });