【发布时间】:2021-02-10 20:26:44
【问题描述】:
我正在尝试 Firebase,我加入了两个表,并希望 node js express 在两个查询结果可用后发送响应
const database = firebase.database().ref();
const posts = database.child('posts');
const user = database.child('user');
let postWithName = [];
let postnames = []
function getUserNames(data) {
if (data) {
postnames = [] // NEW
Object.values(data).forEach((value) => {
user.child(value.user_id).once('value', sn => {
let content = value.content;
let date_posted = value.date_posted;
let id = value.id;
let title = value.title;
let user_id = value.user_id;
let user_Name = sn.val().name;
postnames.push({
"id": id,
"title": title,
"date_posted": date_posted,
"content": content,
"user_Name": user_Name,
"user_id": user_id
})
postWithName = postnames.sort(function (a, b) {
return b.id - a.id;
})
console.log(postnames)
})
})
}
}
function GetAll() {
posts.once('value', snap => {
postdata = snap.val()
getUserNames(postdata)
})
}
app.get('/getPosts', function (req, res) {
GetAll()
res.send({ "posts": postWithName })
})
方案是这样的 用户表示例:
8721da2c-0028-430f-a995-0d03c8abb393:{
IsAdmin: 0,
Password: 123456,
email: 'admin@test.com',
id: 1,
image_file: 'https://i.imgur.com/fjYAIbl.png',
name: 'Abdelrahman',
phone: 1234567890,
public_id: '8721da2c-0028-430f-a995-0d03c8abb393'
}
发布表示例:
6:{
content: 'content 4',
date_posted: '2021-01-06 08:54:44',
id: 6,
title: 'test 4',
user_id: '8721da2c-0028-430f-a995-0d03c8abb393'
},
当使用提供的代码时,我在第一次获取请求时没有获取数据,但是在它之后我根据需要获取数据,我只需要请求等待 firebase 查询完成并填充列表然后发送回应,怎么办?
【问题讨论】:
标签: node.js firebase express firebase-realtime-database