如何使用Firebase实时数据库查询所有子级

时间:2019-11-25 23:48:27

标签: javascript firebase firebase-realtime-database

我正在尝试使云函数查询我的实时数据库

我的结构:

devices_token
   -LuYV_1o8E6hC1hF-STo
       fcmToken:fFLk85eSHyk:APA91bHjRHP0aVH72r0GOeV51nUfpt-REYO..."
   -LuZwn7CQ3SVDWep9aOq
       fcmToken:"fFLk85eSHyk:APA91bHjRHP0aVH72r0GOeV51nUfpt-REYO..."

我的代码:

app.post('/', (req, res) => {
  let {title, id} = req.body;
  admin
  .database()
  .ref('/devices_token/{push_id}')
  .on('value', snapshot => {
    const val = snapshot.val();
    console.log(val);
   });
  });

我得到null

2 个答案:

答案 0 :(得分:1)

您不能在实时数据库引用中使用通配符。相反,我认为您想要在这里做的就是像这样在/devices_token处获取整个树:

app.post('/', (req, res) => {
let {title, id} = req.body;
admin
.database()
.ref('/devices_token')
.once('value', snapshot => {
  const val = snapshot.val();
  console.log(val); // {"-LuYV_...":{"fcmToken":"..."},"...":{...}}
 });
});

答案 1 :(得分:1)

我已经解决了

admin
.database()
.ref('/devices_token')
.once('value', snapshot => {
  snapshot.forEach(function(data) {
    let val = data.val();

    push_token.push(val.fcmToken);
  });
})