Firebase function - query firestore

Ann*_*eke 2 firebase google-cloud-functions google-cloud-firestore

Im trying to retrieve some data from firestore within a cloud function, but get nothing back. The same query on the client-side gives me the correct results. It's probably something small but I don't see the issue. What am I doing wrong?

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
const db = admin.firestore();
db.settings({ timestampsInSnapshots: true });

exports.myFunction = functions.https.onCall((data, context) => {
  const info = getInfo();
  //do some stuff with the info
  return info;
}

function getInfo() {
  const query = db
    .collection('info')
    .where('table_nr', '==', 1)
    .where('number', '<=', 25)
    .orderBy('number', 'desc')
    .limit(1);

  const info = query.get().then(snapshot => {
    snapshot.forEach(doc => {
      return doc.data();
    })
  })
  return info;
}
Run Code Online (Sandbox Code Playgroud)

When I make a call to this function I get: "data: null"

let info = functions.httpsCallable('myFunction')

info().then(res => { console.log(res) })
Run Code Online (Sandbox Code Playgroud)

I tried a lot of different options, like when I change the last part to:

const info = query.get().then(snapshot => {
  snapshot.docs;
})
Run Code Online (Sandbox Code Playgroud)

I get an array with 1 object. So I'm sure there is a document in the query with data. The console.log gives me:

{data: Array(1)}
data: Array(1)
0: {_ref: {…}, _fieldsProto: {…}, _serializer: {…}, _validator: {…}, 
_readTime: {…}, …}
length: 1
__proto__: Array(0)
__proto__: Object
Run Code Online (Sandbox Code Playgroud)

And:

return query.get().then(querySnapshot => {
  if (querySnapshot.empty) {
    return { exists: false }
  } else {
    return { exists: true }
  }
})
Run Code Online (Sandbox Code Playgroud)

The console.log:

{data: {…}}
data:
  exists: true
  __proto__: Object
  __proto__: Object
Run Code Online (Sandbox Code Playgroud)

Mabye good to add that I created an (working) index for the query.

Dou*_*son 5

在这两种情况下,您都会返回一个对象的承诺,而该对象并不是您真正想要发送给客户端的。当您编写一个可调用对象时,您需要返回一个解析为您想要发送的确切JavaScript 对象的承诺。你不能只是返回任何东西。您需要做的是将该 querySnapshot 转换为简单的旧 JavaScript 对象,这些对象描述您希望客户端知道的内容。querySnapshot 对象本身是不可序列化的——它是一个复杂的对象,它描述了关于查询结果的许多事情。

首先定义这个:你到底希望客户收到什么?定义实际的 JavaScript 对象应该是什么样子。现在,将查询结果转换成这样。至少,您可以将整个文档集作为纯 JS 对象发送,如下所示:

return query.get().then(querySnapshot => {
    return querySnapshot.docs.map(doc => doc.data());
})
Run Code Online (Sandbox Code Playgroud)

这将使用原始文档对象向客户端返回一个数组。但我不清楚这就是你想要发送的(因为你没有定义你的期望)。但这是一个开始。