我想更新一个集合中的文档。
my_collection
document_1
field_1
field_2
document_2
field_1
field_2
我的代码:
exports.aggregateUsers =
functions.firestore.document('users/{userId}').onWrite(function(change,
context) {
const document = change.after.exists ? change.after.data() : null;
const oldDocument = change.before.data() || null;
return firestore.runTransaction(function(transaction) {
var oldInstanceRef;
var instanceRef;
var oldInstanceDoc;
var instanceDoc;
if (document != null) {
instanceRef = firestore.collection("counters").doc("instance_counter").collection("instances").doc(document.instance);
instanceDoc = transaction.get(instanceRef);
var newNumberOfUsers = (instanceDoc.data().number_of_users || 0) + 1;
transaction.set(instanceRef, { number_of_users: newNumberOfUsers });
}
if (oldDocument != null) {
oldInstanceRef = firestore.collection("counters").doc("instance_counter").collection("instances").doc(oldDocument.instance);
oldInstanceDoc = transaction.get(oldInstanceRef);
var newPrevNumberOfUsers = (oldInstanceDoc.data().number_of_users || 0) + 1;
transaction.set(instanceRef, { number_of_users: newPrevNumberOfUsers });
}
}).catch(function(error) {
console.log("invalid-argument", error.code, error.message);
});
});
错误:
instanceDoc.data is not a function
由于应用流量低,我正在使用云功能中的事务来汇总用户数量,而不是使用分布式计数器。我的问题是如何更新每个文档中字段的值?谢谢
答案 0 :(得分:2)
我猜你忘了异步/等待。
尝试一下:
async
参数之前的{li> transaction
await
之前transaction.get(<some_ref_here>)
return firestore.runTransaction(async transaction => {
var oldInstanceRef;
var instanceRef;
var oldInstanceDoc;
var instanceDoc;
if (document != null) {
instanceRef = firestore.collection("counters").doc("instance_counter").collection("instances").doc(document.instance);
instanceDoc = await transaction.get(instanceRef);
var newNumberOfUsers = (instanceDoc.data().number_of_users || 0) + 1;
transaction.set(instanceRef, { number_of_users: newNumberOfUsers });
}
if (oldDocument != null) {
oldInstanceRef = firestore.collection("counters").doc("instance_counter").collection("instances").doc(oldDocument.instance);
oldInstanceDoc = await transaction.get(oldInstanceRef);
var newPrevNumberOfUsers = (oldInstanceDoc.data().number_of_users || 0) + 1;
transaction.set(instanceRef, { number_of_users: newPrevNumberOfUsers });
}
}).catch(function(error) {
console.log("invalid-argument", error.code, error.message);
});