0

I'm trying to understand how to handle errors in Mongoose and Javascript in general. If I have this function :

let update = async (userId, age) => {

    const user = await userModel.findOne({ userId: userId });

    if(!user) return "no user !";

    user.age = age;
    
    return await user.save();
}

How can I make it return the string "findOne failed" or "save failed" ? I've been trying to use callbacks but I didn't succeed. The .findOne() and .save() methods are from Mongoose and they accept callbacks as parameters.

Some things I tried :


// in the update function

userModel.findOne({ userId: userId }, (err) => {
   if(err) return "findOne failed";
});

userModel.save((err) => {
   if(err) return "save failed";
});

I think I understand why It doesn't work but I don't know how to do what I explained.

May someone help me please ? Thanks a lot !

raph5000
  • 3
  • 1
  • Does `user.save()` actually return a promise? Or does it accept a callback function? Because you are showing both and that's not that common. Either way, this might help how to think about callbacks: https://felix-kling.de/blog/2019/javascript-callbacks-misconceptions.html – Felix Kling Apr 22 '21 at 10:00
  • Thanks for your answer, the post has been closed because it's a duplicate. To answer your question I think it's a yes. But I'm not sure since I do not yet understand the subject enough. Thanks for the link, I'll try unerstand. Have a nice day – raph5000 Apr 22 '21 at 10:49

0 Answers0