Right now you're reading the root node, and then iterating over its child nodes. That means that child is a snapshot of the key and value of the users node, not of the child nodes under that. You can easily verify that by logging the key of the child node:
firebase.database().ref('/').on('value', (snapshot) => {
snapshot.forEach((child) => {
console.log(child.key);
});
})
This will log:
users
And since the users node does not have a books property, the child.child('books').val() is null.
There are two possible solutions:
Read only the data under the users node, which you do with:
firebase.database().ref('/users').on('value', (snapshot) => {
snapshot.forEach((user) => {
console.log(user.child('books').val());
});
})
Handle the users node in your callback, with something like:
firebase.database().ref('/').on('value', (snapshot) => {
snapshot.child('users').forEach((user) => {
console.log(user.child('books').val());
});
})
In either case you'll likely also want to iterate over the books, so will need a/another nested loop. Something like:
firebase.database().ref('/users').on('value', (snapshot) => {
snapshot.forEach((user) => {
snapshot.child('books').forEach((book) => {
console.log(book.val());
// or: console.log(book.child('author').val());
});
});
})
).after('books'is a typo in the question only. If that's indeed the case, what's the problem when you run this code? What does it log? And what do you want it to log instead?nulllogged in the console from the codeusersnode into account. So you'll either need to do that in the callback, or read one level lower in the tree:firebase.database().ref('users').... I'll write an answer below too.