Adam
Adam

Reputation: 549

Promise in promises array in mongoose

I wrote following code to get all tours of a user. And when getting them I ve updating as follow. Code is perfectly work for parent promises. Tour Status correctly update.. And then I need to get each tour offers count. But the inner promise return null. Can anyone help me to solve this issue.

const response = await Tour.find({ customer: user.id }).sort({
        createdAt: -1
    });

    const toursPromises = response.map(async tour => {
        if (tour.tourStatus === 'new' && tour.transferDate < Date.now()) {
            return await Tour.findByIdAndUpdate(
                tour._id,
                { $set: { tourStatus: 'expired' } },
                { new: true }
            );
        } else if (tour.tourStatus === 'new') {
            return await Tour.findByIdAndUpdate(
                tour._id,
                {
                    $set: {
                        offers: await Offer.find({
                            tour: tour._id,
                            offerStatus: 'new'
                        }).length
                    }
                },
                { new: true }
            );
        } else {
            return tour;
        }
    });

    const tours = await Promise.all(toursPromises);

Upvotes: 0

Views: 105

Answers (1)

trincot
trincot

Reputation: 350077

find() does not return a value with a length property, but a promise. So you need to await find(), not find().length. Use parentheses:

    (await Offer.find({
        tour: tour._id,
        offerStatus: 'new'
    })).length

Remark: maybe such mistakes would occur less often if we paid more attention to how we talk about promises. Don't say "the inner promise returns null", but: "the inner promise resolves to null". Because: promises don't return anything -- they are not functions, but mere objects. These objects change state as they resolve with a value, or reject with a reason.

Upvotes: 2

Related Questions