dimanche 1 mars 2015

Mongoose population call (maybe?) hanging

I'm following the thinkster.io MEAN tutorial - everything works, but I tried to go off-piste a little, and I don't understand why my changes don't work. After my changes, GETting /posts/<id> simply never responds - node logs the request, but no response is sent.


Working code



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();
});
});

router.get('/posts/:post', function(req, res, next) {
req.post.populate('comments', function(err, post) {
if (err) { return next(err); }

res.json(post);
});
});


Broken code


All I've done is move the populate call up to the parameter handler (is that the correct term?) - to my mind, that should work - by the time the GET handler comes around, req.post should have it's comments populated, no?



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')); }

post.populate('comments', function(err, spost) {
if (err) { return next(err); }
req.post = spost;
});

return next();
});
});

router.get('/posts/:post', function(req, res) {
res.json(req.post);
});

Aucun commentaire:

Enregistrer un commentaire