'findOneAndUpdate method returning before resolving

The method is returning undefined. I.g., finishing before the findOneAndUpdate resolves.

exports.updateMovie = async (movie) => {
    try {
        return await Movie.findOneAndUpdate({_id: movie._id}, movie, {upsert: true, new: true}, (err, result) => {
            return result;
        });
    } catch(err) {
        return err;
    }
};


Solution 1:[1]

As the findOneAndUpdate doc says, the method without a callback returns a Query which has to be executed. So to make the method work it should look like:

exports.updateMovie = async (movie) => {
    try {
        return await Movie.findOneAndUpdate({_id: movie._id}, movie, {upsert: true, new: true}).exec();
    } catch(err) {
        return err;
    }
};

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Phil Dukhov