Please help me resolve this error code

My plea for help-
Please, help!

Error message-
MongooseError: Model.findById() no longer accepts a callback at Function.findById

Code-

userModel.findById(userId, (err, userFound) => {
if (err) console.log(err);
console.log(userFound);
newExer.save();

})
res.json({
_id: userFound._id,
username: userFound.username,
description: newExer.description,
duration: newExer.duration,
date: newExer.date.toDateString()
})
})

I’ve looked it up and heard about using async and promises I tried, I failed, now I plead for help.

Post a link to your Replit or a GitHub repo.

Also, looking at the code I assume you are working on the exercise tracker but it would have been nice if you mentioned what challenge you were working on.


All you should need to do is make the route handle async and await the Mongoose method call.

https://mongoosejs.com/docs/api/model.html#model_Model-findById

Or you can downgrade to Mongoose v6 which still supports callbacks.

My plea for help-
Please, help!

Error message-
MongooseError: Model.findById() no longer accepts a callback at Function.findById

Code-

userModel.findById(userId, (err, userFound) => {
  if (err) console.log(err);    
  console.log(userFound);
  newExer.save();
  
  })
  res.json({
    _id: userFound._id,
    username: userFound.username,
    description: newExer.description,
    duration: newExer.duration,
    date: newExer.date.toDateString()
  })
})

I’ve looked it up and heard about using async and promises I tried, I failed, now I plead for help.

I’ve edited your code for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (').

I have merged your threads. Please do not create duplicate topics for the same question.

It looks like you are trying to use the .findById() method of a Mongoose model with a callback, but the current version of Mongoose no longer supports callbacks for this method.

Instead you want to use async/await

Here’s an example of how to use .findById() with async/await:

try {
  const userFound = await userModel.findById(userId);
  console.log(userFound);
  newExer.save();
  res.json({
    _id: userFound._id,
    username: userFound.username,
    description: newExer.description,
    duration: newExer.duration,
    date: newExer.date.toDateString()
  });
} catch (err) {
  console.log(err);
}

In this example, the await keyword is used to wait for the findById() method to return a result before continuing with the code.

If an error occurs, it will be caught in the catch block.

1 Like

Thank you, I see what I was doing wrong when I tried my own catch method