0

I was following a course where the instructor update a mongoose document which looks like this

  .put(authenticate.verifyUser, (req, res, next) => {
    User.findById(req.params.userId) //get the user
      .then(
        (user) => {
          if (user != null && user.comments.id(req.params.commentId) != null) {
            //update the comment
            user.save().then(
              (user) => {
                User.findById(user._id)
                  .then((user) => {
                    //response logic
                  });
              },
              (err) => next(err) //(1) Is this error occur when the .save() throw any error?
            );
          } else if (user == null) {
             //handle error
            return next(err);
          } else {
             //handle error
            return next(err);
          }
        },
        (err) => next(err) //(2) When this error occur?
      )
      .catch((err) => next(err));
  })

But I have a hard time understanding when which error is thrown by (err) => next(err). Can anyone explain it?

emonhossain
  • 378
  • 2
  • 9
falamiw
  • 426
  • 4
  • 16

1 Answers1

0

Rearrange your code like this,

  .put(authenticate.verifyUser, (req, res, next) => {
    User.findById(req.params.userId)
      .then(
        (err,user) => {
          if(err) next(err)
          if (user != null && user.comments.id(req.params.commentId) != null) {
            //update the comment
            user.save().then(
              (err,user) => {
                 if(err) next(err)
                 else {
                    User.findById(user._id)
                    .then((user) => {
                      //response logic
                  });
                 }
              }
            );
          } else if (user == null) {
             //handle error
            return next(err);
          } else {
             //handle error
            return next(err);
          }
        }
      )
      .catch((err) => next(err));
  })

Which will make more sense when the error rises. you can follow this answer for more details.

emonhossain
  • 378
  • 2
  • 9