Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

findOneAndUpdate method returning before resolving

Tags:

mongoose

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;
    }
};
like image 770
Victor Augusto Avatar asked Dec 18 '22 06:12

Victor Augusto


1 Answers

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;
    }
};
like image 104
Victor Augusto Avatar answered Jun 25 '23 22:06

Victor Augusto