0

I'm learning MEAN stack with an awesome tutorial online. In it, there is a section about preloading objects by id using express's param().

router.param('post', function(req, res, next, id) {
  var query = Post.findById(id);

  query.exec(function (err, post){
    if (err) { return next(err); }
    if (!post) { return next(new Error('can\'t find post')); }

    req.post = post;
    return next();
  });
});

My question are:

  1. Where can I find the API documentation on the exec() function? Is it a Mongoose function? How can I tell if it's a Mongoose function or JS or express function?

  2. What's the purpose of final return next() here? Is it necessary in the exec() function to have return next()? What would happen if that line is absent? I have read that next() is for the next middleware, but in other functions from the tutorial, like below, there is no final next() or return next(). What's the difference between next() and return next() anyways?

    router.post('/posts', function(req, res, next) {
      var post = new Post(req.body);
    
      post.save(function(err, post){
        if(err){ return next(err); }
    
        res.json(post);
      });
    });
    

Thanks.

Melissa
  • 1,236
  • 5
  • 12
  • 29

2 Answers2

1

First of all please read document of every library you used, if you read just document of mongoose you figure out what is the exec() !

Ok now we can focus on the point

Q1: The exec() is mongoose function. if you being stuck in this situation which you can't figure out what's going on in code, please check this out. this web app can help you when you need some info about functions (methods) , properties or ... (work perfectly in offline times).

Q2: Please read this question (By the way i think your last question is duplicated)

Community
  • 1
  • 1
Alireza Davoodi
  • 749
  • 7
  • 20
0

MEAN is using express. next() tells the express server to go to invoke the next middleware. http://expressjs.com/guide/using-middleware.html

The exec is not expressjs by the way.

sagie
  • 1,744
  • 14
  • 15
  • as for return next() and not just next(), its is coding convention to call return after calling a callback (in this case next). – sagie Sep 25 '15 at 15:34