Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

retrieve data from Firestore as json

in firestore documentations i found this way to get multi data

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());
    });
})

but this way i have to make two loop one in backend to handle and push data into object then another loop in frontend for display the data !! is there any way to escape the first loop and return list of data without handle it in loop in backend like that

return res.status(200).json(doc.data())

the answer

.get()
.then(query=>{
    let data = query.docs.map(doc=>{
        let x = doc.data()
            x['_id']=doc.id;
            return x;
    })
    res.status(200).json(data);
})

this answer will return an id of doc as part of data it-self

like image 877
Mahmoud Niypoo Avatar asked Oct 28 '25 03:10

Mahmoud Niypoo


1 Answers

according to https://cloud.google.com/nodejs/docs/reference/firestore/0.17.x/QuerySnapshot and https://cloud.google.com/nodejs/docs/reference/firestore/0.17.x/QueryDocumentSnapshot there is no direct way to get the results directly as a json object. If you want a list of data (list means an array, so you will not have the id as index), I would use the array map function: https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Array/map

return db.collection("cities").where("capital", "==", true)
    .get()
    .then(function(querySnapshot) {
        return querySnapshot.docs.map(doc => {...doc.data(), id: doc.id});
    });

if you can not use es6 syntax then replace {...doc.data(), id: doc.id} with

Object.assign(doc.data(), {id: doc.id});

PS: this will return a Promise object and not the array itself, so you will have to use .then() on the returned Promise or the new await syntax

like image 67
Dimitri L. Avatar answered Oct 30 '25 16:10

Dimitri L.