E
E
Evgeny Zapunny2021-06-08 11:08:36
Node.js
Evgeny Zapunny, 2021-06-08 11:08:36

How to await call to mongoose via foreach?

There is an entry in the table that stores the name, description and an array with user ids. It is necessary to walk through this array, wait for each response and write this into an object that I will send to the user, so that at the output he receives the user id, and their object.

console.log('\x1b[33m%s\x1b[0m', "Старт")
await room.users.map(async (id, i) => {
    console.log(`${i} запрос к бд`)
    users[id] = await User.findById(id)
    console.log(`${i} ответ`)
});
console.log('\x1b[36m%s\x1b[0m','Отправлено')

Output to the console like this60bf252398781218545731.png

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Evgeny Zapunny, 2021-06-08
@evgzap

I came up with a different method. I accessed the db in the following way

let arrayUsers = await User.find({_id:{$in:room.users}})

then, through arrayUsers.map(), I added what I wanted to the variable I needed.
arrayUsers.map((elem, i)=>{
    users[elem._id] = elem
})

and everything works.

L
Lynn "Coffee Man", 2021-06-08
@Lynn

No way. Use a regular for (or for .. of).
Or some libraries like bluebirdjs.com/docs/api/promise.mapseries.html or similar.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question