Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make functions work with Firestore?

functions/index.js:

const functions = require('firebase-functions')
const admin = require('firebase-admin')
admin.initializeApp(functions.config().firebase)
const db = admin.database().ref()
exports.app = functions.https.onRequest((req, res) => {
  // do whatever here...
  db.child('something').once('value').then(snap => console.log(snap.key))
})

Above works for Firebase.

I'm interested in making this example work from functions. Something like this but working:

const functions = require('firebase-functions')
const admin = require('firebase-admin')
admin.initializeApp(functions.config().firebase)
const db = admin.database().ref()

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

  let docRef = db.collection("cities").doc("SF")      
  docRef.get().then(doc => {
      if (doc.exists) console.log("Document data:", doc.data())
      else console.log("No such document!")
  }).catch(error => {
      console.log("Error getting document:", error)
  })

})
like image 591
Alin C Avatar asked Oct 04 '17 09:10

Alin C


1 Answers

Use admin.firestore() instead of admin.database(). Be sure your firebase-admin module is 5.4.1 or better.

exports.fun = functions.https.onRequest((req, res) => {
    const store = admin.firestore()
    store.collection('users').doc('foo').get().then(doc => {
        if (doc.exists) {
            console.log(doc.data())
            res.send(doc.data())
        }
        else {
            res.send("Nothing")
        }
    }).catch(reason => {
        console.log(reason)
        res.send(reason)
    })
})
like image 59
Doug Stevenson Avatar answered Oct 06 '22 01:10

Doug Stevenson