I'm in the process of creating a social networking site where users can connect with each other. I am facing an issue in one of my routes where I need to extract posts from the following array of current users, sort them by date, and send them as a single array to the client side. However, the problem is that the posts are not being added to the array before it gets sent to the client. I'm unsure if I should use an async function or some other method.
This is the route for fetching posts:
const express = require('express')
const user = require("../models/user")
const router = express.Router()
router.get("/api/:username/following/posts", (req, res) => {
let following = [...req.user.following, req.user._id]
let posts = [], i;
for(i = 0; i < following.length; i++){
User.findById(following[i]).populate("posts")
.then(user => {
for(let b = 0; b < user.posts.length; b++){
posts.push(user.posts[b])
}
})
.catch(err => {
console.log(err)
})
}
console.log(posts) // returns []
res.json(posts)
})