MichaelSolati / geofirestore-js

Location-based querying and filtering using Firebase Firestore.
https://geofirestore.com
MIT License
504 stars 58 forks source link

question - Want to get data only in the documents as the query #99

Closed davepaiva closed 5 years ago

davepaiva commented 5 years ago
exports.getData = functions.https.onRequest((req, res)=>{
    cors(req, res, ()=>{

        if(req.method === 'POST'){

            var radius = Number(req.body.radius)
            var userLat = Number(req.body.userLat)
            var userLong = Number(req.body.userLong)

            var query = geoCollection.near({ center: new admin.firestore.GeoPoint(userLat, userLong), radius: radius });

            query.get().then((snap)=>{  //returns a Promise
                doc = snap.docs
                return send(doc.data())
            }).catch((err)=>{
                throw res.send(err)
            })

        }else{
            res.status(500).json({
                message: 'Invalid Request'
            })
        }
    })
})

I get a list of all the documents, the list contains doc Ids , distance and exists but not the actual document data. How to do I get the data? Thanks in advance

UPDATE: Tried the following code:

const functions = require('firebase-functions');
const cors = require('cors')({origin: true})   
const admin = require('firebase-admin')
const geofirestore = require('geofirestore');   

var serviceAccount = require('./serviceAccountKey.json');  
admin.initializeApp({
  credential: admin.credential.cert(serviceAccount)      
});

const defaultFirestore = admin.firestore(); 
const  geoFirestore = new geofirestore.GeoFirestore(defaultFirestore); for Geofirestore 
const geoCollection = geoFirestore.collection('trees'); 

   exports.getData = functions.https.onRequest((req, res)=>{

    cors(req, res, ()=>{

        if(req.method === 'POST'){

            var rad = Number(req.body.radius)
            var userLat = Number(req.body.userLat)
            var userLong = Number(req.body.userLong)

            // var query = geoCollection.near({ center: new admin.firestore.GeoPoint(userLat, userLong), radius: radius });

            // query.get().then((snap)=>{  //returns a Promise
            //     doc = snap.docs
            //     return send(doc.data())
            // }).catch((err)=>{
            //     throw res.send(err)
            // })

            const geoQuery = geoCollection.query({center: new admin.firestore.GeoPoint(userLat, userLong), radius: rad})

            // Where we will store the results
            const results = [];

            // As documents come in, push them into our results
            geoQuery.on('key_entered', (key, doc) => results.push(doc));

            // After the query is initially complete we then send the results to the client
            geoQuery.on('ready', () => response.status(200).json(results));

        }else{
            res.status(500).json({
                message: 'Invalid Request'
            })
        }
    })
})

I get the following error on firebase:

TypeError: geoFirestore.query is not a function
    at cors (/user_code/index.js:104:43)
    at cors (/user_code/node_modules/cors/lib/index.js:188:7)
    at /user_code/node_modules/cors/lib/index.js:224:17
    at originCallback (/user_code/node_modules/cors/lib/index.js:214:15)
    at /user_code/node_modules/cors/lib/index.js:219:13
    at optionsCallback (/user_code/node_modules/cors/lib/index.js:199:9)
    at corsMiddleware (/user_code/node_modules/cors/lib/index.js:204:7)
    at exports.getData.functions.https.onRequest (/user_code/index.js:94:5)
    at cloudFunction (/user_code/node_modules/firebase-functions/lib/providers/https.js:57:9)
    at /var/tmp/worker/worker.js:783:7
MichaelSolati commented 5 years ago

Your first function is closer to being right. But I think you should look at what the get function returns. But here's how you can restructure your query:

query.get().then((snap) => {
  const docs = snap.docs.map((doc) => {
    doc['data'] = doc['data']();
    return doc;
  });

  res.status(200).send({ docs });
}).catch((err)=>{
  res.status(500).send(err)
});

Also for your firebase error, you should look at this.

davepaiva commented 5 years ago

Your first function is closer to being right. But I think you should look at what the get function returns. But here's how you can restructure your query:

query.get().then((snap) => {
  const docs = snap.docs.map((doc) => {
    doc['data'] = doc['data']();
    return doc;
  });

  res.status(200).send({ docs });
}).catch((err)=>{
  res.status(500).send(err)
});

Also for your firebase error, you should look at this.

Thank you so much , it worked as expected! Awesome library 10/10 would recomend

JesusGui commented 4 years ago

Tu primera función está más cerca de tener razón. Pero creo que deberías mirar lo getque devuelve la función . Pero así es como puede reestructurar su consulta:

query.get().then((snap) => {
  const docs = snap.docs.map((doc) => {
    doc['data'] = doc['data']();
    return doc;
  });

  res.status(200).send({ docs });
}).catch((err)=>{
  res.status(500).send(err)
});

También para su error de Firebase, debe mirar esto .

¡Muchas gracias, funcionó como se esperaba! Impresionante biblioteca 10/10 recomendaría

hello ,

yo shared me, how access your collection in db firestore :)