javascript - 尝试迭代 Map 元素时出现 TypeError

标签 javascript firebase-realtime-database google-cloud-functions

我试图迭代我认为是 Map 对象的元素并收到以下错误:

TypeError: cr.forEach is not a function
   at exports.onNewOrder.functions.database.ref.onCreate.event (/user_code/index.js:122:12)
   at Object.<anonymous> (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:112:27)
   at next (native)
   at /user_code/node_modules/firebase-functions/lib/cloud-functions.js:28:71
   at __awaiter (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:24:12)
   at cloudFunction (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:82:36)
   at /var/tmp/worker/worker.js:728:24
   at process._tickDomainCallback (internal/process/next_tick.js:135:7)

这是我在 Google Cloud Function 中运行的代码:

function logMapElements(value, key, mapObj) {
    console.log(`m[${key}] = ${value}`);
}    

exports.onNewOrder = functions.database.ref('/orders/{orderId}').onCreate(event => {

    const data = event.val();
    const cr = data.crs;
    console.log(cr);

    cr.forEach(logMapElements);
}

这是 console.log(c) 在日志中打印的内容:

{ cr_36446aba912c45d0956e57cbf0a4e165: 1, cr_d46f4c12119e45478a0aa2867df55e09: 1 }

我在这里做错了什么?

最佳答案

虽然 Sidhanshu_、user9977547 和 Fabien Greard 的答案都可能有效,但我考虑使用 Firebase 的内置 DataSnapshot.forEach更惯用的方法:

exports.onNewOrder = functions.database.ref('/orders/{orderId}').onCreate(event => {
    event.child("crs").forEach(child => {
      console.log(child.val());
    });
}

而结果在Array.forEach()之间和DataSnapshot.forEach()这里是一样的,在其他一些情况下有细微的差别。当您从 Firebase 数据库查询数据时,DataSnapshot.forEach()将按照请求的顺序迭代子级,而当您到达 Array.forEach() 时,您通常会丢失该顺序。 。为了避免细微的错误,我建议使用 DataSnapshot.forEach()用于 Firebase 数据库中的任何数据。

关于javascript - 尝试迭代 Map 元素时出现 TypeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50984912/

相关文章:

node.js - Firebase函数从URL获取参数

javascript - 如何在隐藏字段中使用由 javascript 函数创建的变量?

javascript - 类型 'forEach' 上不存在属性 '{}'

javascript - 使用条件语句对函数进行单元测试

javascript - 更改下拉项

firebase - 如何在不手动导入的情况下将 JSON 文件导入到 firebase

javascript - Google Firebase 函数 : webdriver. io 获取 html 网站的源代码

swift - 如何在 Firebase 中排序和过滤数据?

java - Kotlin 中的 Firebase SDK - onChildChanged 未触发列表中的第一个 child

javascript - Firebase 云函数 - TypeError : Cannot read property 'data' of undefined when data exists