MichaelLearner
MichaelLearner

Reputation: 469

Mongoose method find issue

Why should I call await 2 times, when I've already done await in the model function:

async function model() { return await data.find({}, '-_id -__v') }

If I console.log await data.find({}, '-_id -__v') in the model function, I will see the array with right data.

But in the controller function model function returns a Promise instead of just an array, so I should use await again:

async function controller(req, res) {
    return res.status(200).json(await model())
}

I can't understand why it works that way.

Please, help me figuring this out.

Upvotes: 0

Views: 43

Answers (1)

Thibaud
Thibaud

Reputation: 1095

because when you use async keyword your function will ALWAYS return a promise so using async await can be tricky :P

also you don't need to use await in model() since you are returning data, so I suggest you to use

function model() { return data.find({}, '-_id -__v') }

async function controller(req, res) {
    return res.status(200).json(await model())
}

to explain a little bit more why you don't have to use await in the model() function, that's because data.find() is a promise so you just have to return it, if you use async await you donc return data you also return a promise so there is no need and this can be confusing

Upvotes: 1

Related Questions