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
From the Firestore guide…
and the Node.js API docs…
You could maintain some simple Boolean state outside the listener to determine if it is the initial snapshot or not
Here,
newDocs
will only contain documents added since you started listening.What you’re seeing is the expected behavior. From the documentation on listening for changes between snapshots:
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