0

I am trying to get the user data by setting the track: true. But the updatedBy is returned with user id. I want to push the tracked user data to the element. Inside the user model execution, the element.userDetials is working but not pushing the data to the element. Outside of the user model consoled as undefined.

view.on('init', function (next) {

    var q = keystone.list('Post').paginate({
        page: req.query.page || 1,
        perPage: 5,
        //maxPages: 10,
        // filters: {
        //  state: 'published',
        // },
    })
        .sort('-publishedDate')
        .populate('author categories');

    if (locals.data.category) {
        q.where('categories').in([locals.data.category]);
    }

    q.exec(function (err, results) {
        locals.data.posts = results;
        locals.data.posts.results.forEach(function(element,index){      

            User.model.findById(element.updatedBy).exec(function(error,user){
                element.userDetails = 'Dr. ' + user.name.first + user.name.last;
                console.log(element.userDetails);
                next(error);
            });


        });
        next(err);
    });
});
vam
  • 492
  • 7
  • 17
  • `.forEach()` is not waiting for each async function to complete and also there is a `next(err)` right after that which will actually fire before the loop is complete. You also certainly don't want to call the `next()` callback at all until ALL the work is finished. For a better understanding of async call handling start with the canonical reference as linked. – Neil Lunn May 10 '18 at 09:27
  • So, are you suggesting to use another logic instead of forEach? My problem is not `console.log()` but the value not getting pushed into `element` – vam May 10 '18 at 10:29
  • I know that's the problem. Hence the title of the reference you have been pointed at. I suggest you read it. – Neil Lunn May 10 '18 at 10:30

0 Answers0