简体   繁体   中英

Get real-time updates on specific nested data in Firebase Firestore

I am having trouble getting real-time updates on data stored in Firebase Firestore, the data is organized in the following structure: MsgStatuses -> GroupId -> MessageId -> UserId(data).

I am trying to get a snapshot of changes when there is a change in GroupId and MessageId. I have tried using the following code, but it is not working:

const db = firebase.firestore();
const collectionRef = db.collection("MsgStatuses").doc("176")

collectionRef.onSnapshot((snapshot) => {
  console.log("Data has changed:", snapshot.data());
});

I would like to know how to correctly get the snapshot of changes in GroupId and MessageId in Firebase Firestore.

Read operations (including realtime listeners) in Firestore are shallow; so reading document /MsgStatuses/176 does not then also read the subcollections under it.

If you want to listen to a specific message for a specific group ID, you will need to know that message ID, and then listen for:

const collectionRef = db.collection("MsgStatuses").doc("176").collection("your message ID");

collectionRef.onSnapshot((snapshot) => {
  snapshot.forEach((doc) => {
    console.log(doc.data());
  })
});

For more on this, also see the documentation on listening for multiple documents .


As said above, you will need to know the message ID for this to be possible. The client-side SDKs for Firestore have no API to get a list of all subcollections under a path. For more on this, see: How to list subcollections in a Cloud Firestore document

If you can't know the message ID, you'll want to consider changing your data model so that either you can know the message ID (eg by storing it in the parent document), or so that the messages are stored as documents: /MsgStatuses/$groupId/messages/$messageId . So with this structure, you can listen for all messages for a group with:

db.collection("MsgStatuses").doc("176").collection("messages")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM