0

I'm new in fullstack developing and I'm trying to do a function, in a REST API firebase project, that could filter my collection post by a friend list (gived as a sting with usernames separated by comma, ex:"user1,user2,user3"). After resolve, it gaves me an empty array but I've checked that all the data are correct. What can I do?

exports.getAllPosts = (req, res)=>{                                           //namespace delle funzioni,area https, onRequest  prende una richiesta ed una rispsota
var posts = [];                                         //array per i post

db
.doc(`/users/${req.user.handle}`).get()
.then(doc =>{
    var friends = doc.data().friends.split(',')
    friends.forEach(item=>{
        db
        .collection('posts')
        .where('userHandle','==', `${item}`)
        .orderBy('createdAt','desc')
        .get()                                                      //carica tutta la collezione posts
        .then(data =>{
            data.forEach(doc=>{                                     // ciclo per popolare l'array
                posts.push({
                    postId: doc.id,
                    body: doc.data().body,
                    game:doc.data().game,
                    userHandle: doc.data().userHandle,
                    createdAt: doc.data().createdAt,
                    ggCount: doc.data().ggCount,
                    commentCount: doc.data.commentCount,
                    userImage: doc.data().userImage
                });
            });  
        })
    })        
    return res.json(posts);
    
})
.catch(err => console.error(err));

}

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Loki00
  • 259
  • 3
  • 4
  • 12

1 Answers1

0

You're returning the posts array without waiting for it to be populated first. The db operations you're making are asynchronous, meaning when they complete the respective .then() block is executed; but the code below is executed right away.

I would rewrite it like this:

exports.getAllPosts = (req, res)=>{                                           //namespace delle funzioni,area https, onRequest  prende una richiesta ed una rispsota
    var posts = [];                                         //array per i post
    
    db
    .doc(`/users/${req.user.handle}`).get()
    .then(async doc => {
        var friends = doc.data().friends.split(',');
        for(const friend of friends) {
            const data = await db
                            .collection('posts')
                            .where('userHandle','==', `${friend}`)
                            .orderBy('createdAt','desc')
                            .get();

            data.forEach(doc => {                                     // ciclo per popolare l'array
                posts.push({
                    postId: doc.id,
                    body: doc.data().body,
                    game:doc.data().game,
                    userHandle: doc.data().userHandle,
                    createdAt: doc.data().createdAt,
                    ggCount: doc.data().ggCount,
                    commentCount: doc.data.commentCount,
                    userImage: doc.data().userImage
                });
            });
        }       
        return res.json(posts);
        
    })
    .catch(err => console.error(err));

More on promises.

domenikk
  • 1,723
  • 1
  • 10
  • 12