Firestore not showing updated document after array update
我在Firebase中具有云功能,它使用以下方法更新文档中的数组:
https://firebase.google.com/docs/firestore/manage-data/add-data#update_elements_in_an_array
但是,当我尝试获取该文档的更新版本时,它显示的是数组更新之前的内容。这是我的代码:
eventUpdated在阵列更新之前未显示正确的版本。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | 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; } |
您正在调用一组异步
因此,还应将
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | 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 Cloud Function。请注意,您不需要执行
还请注意,如果连续调用多个文档写入或更新,则可能使用批处理写入。