【发布时间】:2021-06-20 10:14:42
【问题描述】:
这是我的代码:
exports.updateUserName = functions.firestore
.document("users/{userId}")
.onUpdate((change, context) => {
const newValue = change.after.data().name;
const previousValue = change.before.data().name;
const userID = context.params.userId;
var batch = admin.firestore().batch();
if (newValue != previousValue) {
//Update author in sets/{set_id}/author
admin
.firestore()
.collection("sets")
.where("authorId", "==", userID)
.get()
.then((querySnapshot) => {
if (!querySnapshot.empty) {
querySnapshot.forEach((doc) => {
batch.update(doc.ref,{ "author": newValue });
});
}
}),
//Update author in courses/{course_id}/author
admin
.firestore()
.collection("courses")
.where("authorId", "==", userID)
.get()
.then((querySnapshot) => {
if (!querySnapshot.empty) {
querySnapshot.forEach((doc) => {
batch.update(doc.ref,{ "author": newValue });
});
}
})
}
return batch.commit().then(() => {
console.log("commited")
});
});
所以我想更新两个不同的文档。我想我必须用批处理()来做到这一点。 但我得到了错误:
Error: Cannot modify a WriteBatch that has been committed.
at WriteBatch.verifyNotCommitted (/workspace/node_modules/@google-cloud/firestore/build/src/write-batch.js:117:19)
at WriteBatch.update (/workspace/node_modules/@google-cloud/firestore/build/src/write-batch.js:313:14)
at /workspace/index.js:84:21
at QuerySnapshot.forEach (/workspace/node_modules/@google-cloud/firestore/build/src/reference.js:748:22)
at /workspace/index.js:83:33
at processTicksAndRejections (internal/process/task_queues.js:97:5)
这是我第一次使用批处理或必须使用一个云功能更新 2 个文档。 我做错了什么?
【问题讨论】:
标签: javascript node.js firebase google-cloud-firestore google-cloud-functions