6

函数/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))
})

以上适用于 Firebase。

我有兴趣使这个示例从函数中工作。像这样但有效的东西:

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

})
4

1 回答 1

18

使用admin.firestore()而不是admin.database(). 确保您的 firebase-admin 模块是 5.4.1 或更高版本。

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)
    })
})
于 2017-10-04T14:59:28.423 回答