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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With