skip to Main Content

I am trying to only listen to documents that where only added to the collection. However if i exit node and run the js file again it will return the entire collection an not the newly created one. How can i return just the newly created document.

Below is my code any help would be highly appreciated.

const db = getFirestore();

const doc = db.collection("orders");

const observer = db.collection("orders").onSnapshot((querySnapshot) => {
  querySnapshot.docChanges().forEach((change) => {
    if (change.type === "added") {
      console.log(change.doc.data());
    }
  });
});

2

Answers


  1. From the Firestore guide

    Important: The first query snapshot contains added events for all existing documents that match the query. This is because you’re getting a set of changes that bring your query snapshot current with the initial state of the query

    and the Node.js API docs

    If this is the first snapshot, all documents will be in the list as added changes.

    You could maintain some simple Boolean state outside the listener to determine if it is the initial snapshot or not

    const db = getFirestore();
    
    const doc = db.collection("orders");
    
    let initialSnapshot = true;
    
    const observer = db.collection("orders").onSnapshot((querySnapshot) => {
      if (initialSnapshot) {
        initialSnapshot = false;
        return;
      }
      const newDocs = querySnapshot
        .docChanges()
        .filter(({ type }) => type === "added")
        .map(({ doc }) => doc);
    });
    

    Here, newDocs will only contain documents added since you started listening.

    Login or Signup to reply.
  2. What you’re seeing is the expected behavior. From the documentation on listening for changes between snapshots:

    The first query snapshot contains added events for all existing documents that match the query.

    If you only want to get changes since a certain moment, you’ll have to store a timestamp in each document and then filter in that field

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search