"The Requested Snapshot Version Is Too Old." Error in Firestore

Firestore query never completes inside Google Cloud Event Trigger Function

I so was hyper-focused on the .collection().get() and never thought about the way the trigger works:

.onUpdate(async (change, context) => {
//do stuff here
});

The trigger itself is async. Adding an await to the function call I run from here gave me the expected result.

    .onUpdate(async (change, context) => {
const result = await doTheStuff(context.params.id, change.after.data().name);
console.log(result);
});

The content of doTheStuff now looks like this and works properly.

async function doTheStuff(){
console.log("-------------------------------------------------start");
await admin
.firestore()
.collection("users")
.get()
.then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
console.log(doc.data().name);
});
})
.catch((error) => {
console.log(error);
});
console.log("-------------------------------------------------end");

return "done with the stuff";
}

The fact that it worked locally misled be to believe it couldn't be code issue when in fact it was.

Thanks to those that had recommendations.

EDIT

Using generally accepted syntactic style for promises...

const db = admin.firestore();
try {
const querySnapshot = await db.collection("users").get();
querySnapshot.forEach(doc => {
console.log(doc.data().name);
});
} catch (error) {
console.log(error);
}

How to read a lot of documents (1M+) from a collection in Cloud Firestore?

Since you're initially calling getData() without any arguments, that leads to doc being undefined in that function body. And calling startAfter(undefined) is not valid.

What you'll want to do is optionally adding that startAfter with something like:

async function getData(doc) {
let query = global.db.collection('Collection').orderBy();
if (doc) {
query = query.startAfter(doc);
}
let snapshot = await query.limit(5000).get();
...

How to process firestore query as i am getting snapshot result as FIRQuerySnapshot`

If you run a query against a collection, the result you get is a QuerySnapshot that contains (possibly) multiple documents. To get each document, you need to loop over the results. From the Firebase documentation on reading multiple documents:

db.collection("cities").whereField("capital", isEqualTo: true)
.getDocuments() { (querySnapshot, err) in
if let err = err {
print("Error getting documents: \(err)")
} else {
for document in querySnapshot!.documents {
print("\(document.documentID) => \(document.data())")
}
}
}

So your code is jut missing the loop from that else block. Something like:

wallpaperRef.getDocuments(completion: { (snap, error) in
if error == nil {
print(snap)
} else {
for document in snap!.documents {
print("\(document.documentID) => \(document.data())")
}
}
})


Related Topics



Leave a reply



Submit