Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: next is not a function

I'm running a Node.js-server and trying to test this Rest API that I made with Express. It's linked up to MongoDB using Mongoose.

I'm testing the individual routes using Postman and I get an error when trying to send a PUT-request to this route:

// PUT /meetings/:id
// Route for editing a specific meeting
router.put("/:id", function(req, res, next) {
    req.meeting.update(req.date, function(err, result) {
      if(err) return next(err);
      res.json(result);
    });
});

The error retrieved is this:

events.js:141
      throw er; // Unhandled 'error' event
      ^

TypeError: next is not a function

I cannot figure out where exactly this is coming from. I'm using the router.params-method to specify how the :id-parameter should be handled like this:

router.param("id", function(req, res, id, next) {
  Meeting.findById(id, function(err, meeting) {
    if (err) return next(err);
    if (!meeting) {
      err = new Error("Meeting not found");
      err.status = 404;
      return next(err);
    }
    req.meeting = meeting;
    return next();
  });
});
like image 272
SudokuNinja Avatar asked Mar 19 '17 13:03

SudokuNinja


2 Answers

So I figured it out. It was a much smaller error than I thought. I had the parameters to the callback-function in my router.param-method in the wrong sequence. The next-keyword should be where id was. This code fixed the problem:

router.param("id", function(req, res, next, id) {
  Meeting.findById(id, function(err, meeting) {
    if (err) return next(err);
    if (!meeting) {
      err = new Error("Meeting not found");
      err.status = 404;
      return next(err);
    }
    req.meeting = meeting;
    return next();
  });
});
like image 199
SudokuNinja Avatar answered Oct 07 '22 02:10

SudokuNinja


Not an answer but just wanted to say that it's so easy to find error like these if you use Promises instead of nested callbacks. An example of above code refactorized.

router.param("id", (req, res, id) => {
  Meeting.findById(id)
    .then(meeting => { meeting })
    .catch(err => res.status(404).send("Meeting not found"))
});
like image 28
Jamie Avatar answered Oct 07 '22 04:10

Jamie