问题
In my application I am using the Firebase Realtime Database and each user can make one or more posts. These posts are stored under /posts and each post contains a userId object.
How do I make a query to count the number of posts made by a particular user with this database structure?
I am using Typescript & Angular 8.
回答1:
Let's say the user you wished to query had the ID -LwSHv8HcYek347sEmXT. You could search for posts using a sorting and filtering by the post author using:
let userId = '-LwSHv8HcYek347sEmXT';
let query = firebase.database.ref('posts').orderByChild('userId/key').equalTo(userId);
query.once('value')
.then((querySnapshot: DataSnapshot) => {
let postCount = querySnapshot.numChildren();
// do something with postCount
// do something with each post's data if you need
querySnapshot.forEach((postSnapshot: DataSnapshot) => {
});
})
.catch((err: any) => {
console.log('Error counting posts: ', err);
});
来源:https://stackoverflow.com/questions/59443783/how-can-i-count-the-number-of-posts-from-another-user