I am working on a Firebase Cloud Function to take all the data in a Firestore collection and put it into the Firebase Realtime Database.
When I run my code (at the bottom of the post) in the Firebase functions emulator, the console.log
on line 9 prints a bunch of keys paired to a bunch of empty objects, like so (actual IDs redacted):
{
'<some id>': {},
'<some other id>': {},
<bunch of other entries>...
}
This doesn't make sense to me, as the documentation doesn't say why it should return an empty object. My documents do exist, so why can't I get their data?
Here is the source code with the problematic segment mented:
exports.generateCache = functions.https.onRequest((req, res) => {
admin.firestore().collection('parts').select().get()
.then(snapshot => snapshot.docs)
.then(docs => {
// this is the problematic segment of code
var cache = {}
docs.forEach(doc => {
cache[doc.id] = doc.data()
})
console.log(cache)
return cache
})
.then(cachedData => storeCachedData(cachedData))
.then(() => {
res.send('done!')
res.end()
})
})
I am working on a Firebase Cloud Function to take all the data in a Firestore collection and put it into the Firebase Realtime Database.
When I run my code (at the bottom of the post) in the Firebase functions emulator, the console.log
on line 9 prints a bunch of keys paired to a bunch of empty objects, like so (actual IDs redacted):
{
'<some id>': {},
'<some other id>': {},
<bunch of other entries>...
}
This doesn't make sense to me, as the documentation doesn't say why it should return an empty object. My documents do exist, so why can't I get their data?
Here is the source code with the problematic segment mented:
exports.generateCache = functions.https.onRequest((req, res) => {
admin.firestore().collection('parts').select().get()
.then(snapshot => snapshot.docs)
.then(docs => {
// this is the problematic segment of code
var cache = {}
docs.forEach(doc => {
cache[doc.id] = doc.data()
})
console.log(cache)
return cache
})
.then(cachedData => storeCachedData(cachedData))
.then(() => {
res.send('done!')
res.end()
})
})
If you check here of the firebase docs. The code sample for querying multiple docs in a collection is:
db.collection("cities").where("capital", "==", true)
.get()
.then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
// doc.data() is never undefined for query doc snapshots
console.log(doc.id, " => ", doc.data());
});
})
.catch(function(error) {
console.log("Error getting documents: ", error);
});
So in your case, try changing this:
.then(snapshot => snapshot.docs)
.then(docs => {
// this is the problematic segment of code
var cache = {}
docs.forEach(doc => {
cache[doc.id] = doc.data()
})
to this
.then(snapshot => {
var cache = {}
snapshot.forEach(doc => {
cache[doc.id] = doc.data()
})
Firestore Snapshot To Object:
db.collection('collection').then(snapshot =>
const docsDictionary = (snapshot.docs || []).reduce((prev, doc) => ({ ...prev, [doc.id]: doc.data() }), {})
// ...do stuff
)