0

I'm working on my nodejs project and I just noticed that waiting for mongoose queries inside an async .map() iteration returns null.

    const arr = [1, 2, 3, 4]
    const result = arr.map(async obj => {
        return {
            number: obj,
            user: await User.findOne({role: 'admin'})
        }
    })
    Promise.all(result).then(res => {
        console.log(result)
    })
    res.sendStatus(200)

log:

[
  Promise { { number: 1, user: null } },
  Promise { { number: 2, user: null } },
  Promise { { number: 3, user: null } },
  Promise { { number: 4, user: null } }
]

How can I get the data from mongoose inside an async Array.prototype.map() properly?

2 Answers 2

1
const arr = [1, 2, 3, 4]
const result = arr.map(async obj => {
    return {
        number: obj,
        user: await User.findOne({role: 'admin'}).exec()
    }
})
Promise.all(result).then(res => {
    console.log(result)
})
res.sendStatus(200)

note the .exec() after findOne

Sign up to request clarification or add additional context in comments.

1 Comment

the output stays the same.
0

I would probably add that if you are doing a findOne with a role admin mongo will probably return the same document all the time.

1 Comment

Oh yes, but just made this up as an example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.