我在Firebase中有一个云函数,它使用以下方法更新文档中的数组:https://firebase.google.com/docs/firestore/manage-data/add-data#update_elements_in_an_array
但是,当我尝试获取文档的更新版本时,它会显示数组更新之前的内容。这是我的代码:
eventUpdated在阵列更新之前未显示正确的版本。
if(isPut(request)){
//All new additions
const userId = request.body.userId;
const eventId = request.body.eventId;
const attStatus = request.body.attStatus;
try {
let eventsRef = db.collection('events').doc(eventId);
if (attStatus === true) {
// Add a new ID to the "eventAttendanceList" array field.
let arrUnion = eventsRef.update({
eventAttendanceList: admin.firestore.FieldValue.arrayUnion(userId)
});
// Remove a ID from the "eventNonAttendanceList" array field.
let arrRm = eventsRef.update({
eventNonAttendanceList: admin.firestore.FieldValue.arrayRemove(userId)
});
}
else if (attStatus === false) {
// Add a new ID to the "eventNonAttendanceList" array field.
let arrUnion = eventsRef.update({
eventNonAttendanceList: admin.firestore.FieldValue.arrayUnion(userId)
});
// Remove a ID from the "eventAttendanceList" array field.
let arrRm = eventsRef.update({
eventAttendanceList: admin.firestore.FieldValue.arrayRemove(userId)
});
}
else {
//If you do anything other than true or false, it will just remove the userId from both attending and non-attending
let arrUnion = eventsRef.update({
eventAttendanceList: admin.firestore.FieldValue.arrayRemove(userId)
});
let arrRm = eventsRef.update({
eventNonAttendanceList: admin.firestore.FieldValue.arrayRemove(userId)
});
}
let eventUpdated = await db.collection('events').doc(eventId).get()
return response.status(200).json({status: "200", message: "Event RSVP successfully updated", event: eventUpdated.data()}).send;
} catch(err) {
return response.status(500).json({status: "500", message: "Event RSVP could not be updated"}).send;
}
} else {
return response.json({status: "ERR", message: "Please send a PUT request."}).send;
}
您正在调用一组异步update()
方法,但在调用get()
方法并发送响应之前,您不会等待它们完成。
因此,对于update()
方法,您也应该使用await
,如下所示:
let eventsRef = db.collection('events').doc(eventId);
if (attStatus === true) {
// Add a new ID to the "eventAttendanceList" array field.
await eventsRef.update({
eventAttendanceList: admin.firestore.FieldValue.arrayUnion(userId)
});
// Remove a ID from the "eventNonAttendanceList" array field.
await eventsRef.update({
eventNonAttendanceList: admin.firestore.FieldValue.arrayRemove(userId)
});
}
else if (attStatus === false) {
//...
}
else {
//...
}
let eventUpdated = await db.collection('events').doc(eventId).get()
response.status(200).json({ status: "200", message: "Event RSVP successfully updated", event: eventUpdated.data() }).send;
我假设您使用的是HTTP云函数。请注意,您不需要执行return
,只需调用response.redirect()
、response.send()
或response.end()
即可。请参阅文档和相应的视频。
还要注意,如果在一行中调用多个文档写入或更新,则可能会使用批处理写入。