【问题标题】:Cannot get data from document in cloud functions (return undefined)无法从云函数中的文档中获取数据(返回未定义)
【发布时间】:2019-05-21 10:57:38
【问题描述】:

我有一个包含 2 个字段的文档:field1,field2(为简单起见更改了名称。

从云函数中,我试图从 field1 中获取值。这些函数不是该特定文档的触发器,我得到的值如下:

const user_collection = db.collection("user")
const photoName = user_collection.doc(userid).field1

但是,我在undefined 中得到的回报。我尝试使用 data() 或 get() 方法,但最终出现错误...is not a function。在文档或 SO 中找不到任何帮助我从文档中获取字段值的内容。

关于如何提取该字段的任何建议?

编辑:

exports.onUserDeletion = functions.auth.user().onDelete((user) => {

    const userid = user.uid
    const photoName = user_collection.doc(userid).photo    //<--- this is "undefined"
    const filePath = `user_photo/${photoName}`
    const file = bucket.file(filePath)

    console.log(`userid: ${userid} photoName: ${photoName} filePath: ${filePath} file: ${file}`)

    return highscore_collection.doc(userid).delete().then(user => {
        return user_collection.doc(userid).delete().then(user => {
            return file.delete()
        })
    })

})

【问题讨论】:

  • 添加你的云功能和你的数据库截图
  • 阅读文档应该会有所帮助:cloud.google.com/firestore/docs/query-data/…
  • @PeterHaddad 我编辑了我的问题以添加这些。
  • 你怎么知道它的未定义?控制台日志?
  • @SomeshMukherjee 是的,完全正确。我也用 console.log() 部分在我的整个函数中编辑了我的问题。

标签: javascript firebase google-cloud-firestore google-cloud-functions


【解决方案1】:

您应该执行以下操作:

exports.deleteUser = functions.firestore.document('user/{userID}').onDelete((snap, context) => {
        const deletedValue = snap.data().photo;
});

来自docs

您还可以使用带有通配符的onDelete() 函数在删除文档时触发函数。


在您的代码中,您使用的是 authentication trigger,这就是您无法访问文档中的 photo 字段的原因。

来自docs

onDelete

每次删除 Firebase 身份验证用户时触发的事件处理程序。

onDelete() 有一个UserRecord 类型的参数。你可以在这里查看UserRecord的属性:

https://firebase.google.com/docs/reference/functions/functions.auth.UserRecord.html

【讨论】:

    【解决方案2】:

    用户已被删除。这就是为什么从数据库中获取它不起作用的原因。

    exports.onUserDeletion = functions.auth.user().onDelete((user) => {   
            const userid = user.uid
            const photoName = user.photo    //<--- this is "undefined"
            const filePath = `user_photo/${photoName}`
            const file = bucket.file(filePath)
    
            console.log(`userid: ${userid} photoName: ${photoName} filePath: ${filePath} file: ${file}`)
    
            return highscore_collection.doc(userid).delete().then(user => {
                return user_collection.doc(userid).delete().then(user => {
                    return file.delete()
                })
            })
    
        })
    

    【讨论】:

      猜你喜欢
      • 2018-03-28
      • 1970-01-01
      • 2019-05-16
      • 1970-01-01
      • 1970-01-01
      • 2018-10-18
      • 1970-01-01
      • 1970-01-01
      • 2012-12-14
      相关资源
      最近更新 更多