I'm trying to change the comments in each post by the number of comments, but The arrays keep the original data when I put in the answer of express.
I tried use another Object and map instead foreach but nothing works.
router.get('/', function(req, res, next) {
postModel.find({}, function(err, posts){
if(err){
next(err)
}else{
posts.forEach((post,i) => {
posts[i].comments= post.comments.length;
});
res.json({ status: 'success' ,message: "Posts Encontrados!!" , data : {posts: posts}});
}
});
});
New code:
router.get('/', async function(req, res, next) { //get all posts
var p;
await postModel.find({}, function(err, posts){
if(err){
next(err)
}else{
p= posts;
//res.json({ status: 'success' ,message: "Posts Encontrados!!" , data : {posts: posts}});
}
});
p.forEach((post,i) => {
p[i].comments= post.comments.length;
});
res.json({ status: 'success' ,message: "Posts Encontrados!!" , data : {posts: p}});
});