Search code examples
restmongoosefindoneandupdate

findOneAndUpdate() no longer accepts a callback


I am a student currently learning on full-stack.

I'm trying to complete an assignment where I am creating an app which allows users to retrieve details on list of movies etc.

There's this app.put where users can update their username:

// UPDATE - user update username

app.put('/users/:Username', (req, res) => {
    Users.findOneAndUpdate (        
        { Username: req.params.Username},
        {
            $set: {
                Username: req.body.Username,
                Password: req.body.Password,
                Email: req.body.Email,
                Birthday: req.body.Birthday
            }
        },
        { new: true },
        (err, updatedUser) => {
            if (err) {
                console.error(err);
                res.status(500).send('Error: ' + err);
            } else {
                res.json(updatedUser);
            }
        })
    ;
});

I am using Postman to try out above code.

It keep stating findOneAndUpdate() no longer accepts a callback.

I have been trying to figure out how to solve it but to no avail.

Could you advise on how to fix the code please?

Have tried googling but can't solve


Solution

  • Call back functions were dropped in Mongoose v7.x. Read more here.

    Solution

    Use try catch instead! And mongoose you need to use an async function and await keyword before your Model.query({}).

    Updated code:

    app.put('/users/:Username', async function(req, res) {
        let updatedUser;
        try{
            updatedUser = await Article.findOneAndUpdate(
            { 
                Username: req.params.Username
            },
            {
                $set: {
                    Username: req.body.Username,
                    Password: req.body.Password,
                    Email: req.body.Email,
                    Birthday: req.body.Birthday
                }
            },
            { 
                new: true 
            });
        }
        catch(err){
            console.error(err);
            return res.status(500).send('Error: ' + err);
        }
        return res.json(updatedUser);
    }
    

    Hope this helps!