Let Me Tink About It
Let Me Tink About It

Reputation: 16102

How to fetch latest added document in a collection in Firebase / Google Cloud Firestore?

Using the web/JS platform, I want to retrieve the latest document added to a collection.

  1. How do I accomplish this?
  2. Do I need to append a timestamp when I save the data?
  3. Does the server automatically append a timestamp in the background on doc.add()?
https://firebase.google.com/docs/firestore/query-data/get-data
db
  .collection("cities")
  // .orderBy('added_at', 'desc') // fails
  // .orderBy('created_at', 'desc') // fails
  .limit(1)
  .get()
  .then(querySnapshot => {
    querySnapshot.forEach(doc => {
      console.log(doc.id, " => ", doc.data());
      // console.log('timestamp: ', doc.timestamp()); // throws error (not a function)
      // console.log('timestamp: ', doc.get('created_at')); // undefined
    });
  });

Upvotes: 3

Views: 3441

Answers (1)

Angus
Angus

Reputation: 3728

You could try using the onSnapshot method to listen to change events:

db.collection("cities").where("state", "==", "CA")
    .onSnapshot(function(snapshot) {
        snapshot.docChanges().forEach(function(change) {
            if (change.type === "added") {
                console.log("New city: ", change.doc.data());
                //do what you want here!
                //function for rearranging or sorting etc.
            }
            if (change.type === "modified") {
                console.log("Modified city: ", change.doc.data());
            }
            if (change.type === "removed") {
                console.log("Removed city: ", change.doc.data());
            }
        });
    });

Source: https://firebase.google.com/docs/firestore/query-data/listen

Upvotes: 3

Related Questions