0

Here is part of my router:

        if (limit <= 100) {
        let id = jwt.verify(req.cookies.tokenlogin, config.get('jwtSecret')).userId
        const results = await User.paginate({ $and: [{ _id: { $ne: id }, fullname: { $regex: search, $options: '-i' } }] },
            { page: page, limit: limit, customLabels: myCustomLabels, lean: true, select: '-email -password' });
        let paginator = results.paginator;
        let arrayRes = results.items;
        await arrayRes.forEach(async (current, i) => {
            await User.findOne({ _id: id }, async (er, rs) => {
                current['followed'] = await rs.followings.includes(current.id);
            })
        })
        res.status(200).json({ items: arrayRes, paginator: paginator })
    }

I used await, but it does not work, server always sent not updated array to the client. How can i sent modified array in my response?

  • `forEach` returns undefined and `includes` doesn't return a promise either. `await` should be used on promises. It's unclear what exactly you're attempting to achieve here, but it's important to be judicious about where `await` is used. Looks like you might need `Promise.all` but it's unclear. Can you share a [mcve] with expected output? Thanks! – ggorlen Jan 12 '20 at 16:34
  • 1
    Can you share the signature of this function? and do you use async? – MEDZ Jan 12 '20 at 16:37
  • Make sure that 'User.paginate()' is async function. For example you can take a look here: https://stackoverflow.com/questions/44512388/understanding-async-await-on-nodejs – Serhii Matvienko Jan 12 '20 at 16:44
  • Also don't pass a callback to `User.findOne` (especially not an `async` one), so that it will return a promis. – Bergi Jan 12 '20 at 16:53
  • RESOLVED. Was resolved by transferring the function `User.findOne` to a variable: `user = await User.findOne(..)` and next working with user variable : `user.followings.include(...)` Thank you all for your help. – Constantine Jan 12 '20 at 19:19

0 Answers0