I have 2 data on my watcher field, first one has availability child and the second one doesn't have..
router.get('/getNewWatcher/:sdate/:shft/:type', function (req, res) {
reqDate = req.params.sdate;
reqShift = req.params.shft;
reqType = req.params.type;
var watcher = database.ref('watchers');
watcher.once('value', function (snapshot) {
var promises = [];
snapshot.forEach(function (childSnapshot) {
promises.push(new Promise((resolve, reject) => {
resolve({
childKey: childSnapshot.key,
childData: childSnapshot.val()
});
}));
});
Promise.all(promises).then(function (snapshot) {
var dataSet =[];
snapshot.forEach(function (result) {
if (result.childData.availability) {
dataSet.push({
child: result
})
}else {
dataSet.push({
child: 'No Available Watchers'
})
}
});
res.json(dataSet);
})
});
});
My code works.. when I run this script to check if a watcher has availability child it will return a watcher which has the availability child.. but for some reason else
conditions also return 'No Available Watchers'
so my problem is when I run this script both my if
and else
condition return a result which isn't quite what I'm looking for and I cant figure it out why.
Here is my Firebase architecture
I used same thing in Swift, here is its code maybe it's useful to understand.
databaseRef.child("users").child(key).child("following").observeSingleEventOfType(.Value, withBlock: { snapshot in
if let following = snapshot.value as? [String : AnyObject] {
self.lblFollowing.text = String(following.count)
} else {
self.lblFollowing.text = "00"
}
})
From your comment chain with Jaromanda XI have the impression that you want to return a list of available watchers, or a single "No Available Watchers" when there are no watchers available anywhere.
To do this you have to move the "no watchers at all" detection outside of the loop:
var dataSet =[];
snapshot.forEach(function (result) {
if (result.childData.availability) {
dataSet.push({
child: result
})
}
});
if (dataSet.length === 0) {
dataSet.push({
child: 'No Available Watchers'
})
}
res.json(dataSet);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.