How to resend the data in for loop in express

Viewed 20

I am checking if whos the user has logged in through session, then going through that user friend list and and creating a for loop through each friend post and share them to home page that can be displayed. But I am not able to find a way to do this. I tried looping through friend list and adding them to array and sharing it, but it seems it list looses its data as page is refreshed. Kindly suggest me a way to do this.

My schema,

const userSchema = new mongoose.Schema({
  username:String,
  password:String,
  posts: [postSchema],
  friends:[]
});
const postSchema = new mongoose.Schema({
  name:String,
  content:String,
  likes:[],
  timeStamp:String
});

My code

app.route("/home").get((req,res)=>{
  if(req.isAuthenticated()){
    var postList= [];
    User.findOne({username:req.session.passport.user},(err,result)=>{      // this is for searchig through list for loggined person data.
      if((result.friends).length!==0){
        for(let i=0;i<(result.friends).length;i++){                     //going through his friends list
          User.findOne({username:result.friends[i]},(err,data)=>{     //for each friend adding that to list to pass to home page to display.
            if(err){
              console.log(err);
            }
            else{
              postList.push(data.posts);
            }
          });
        }
        res.render("home",{name:req.session.passport.user,tweets:postList})
      }
      console.log(postList);
    });
  }
  else{
    res.redirect("/login");
  }
})

I am new to this, kindly help. ty.

0 Answers
Related