Sunday 17 January 2016

Help Needed: how are Express routes (REST)used to save to Mongo Databases?

I'm a bit new to this, but I'm afraid I'm missing a piece of information and hoping you can help me understand.Specifically, I'm working through the thinkster.io MEAN tutorial on the REST Routes portion. http://ift.tt/1OYaN8d works according to the tutorial, but I'm not understanding exactly how the second to last snippet works.router.post('/posts/:post/comments' function(req,res,next) { var comment = new Comment(req.body); comment.post = req.post; comment.save(function(err,comment) { if (err) {return next(err); } req.post.comments.push(comments); req.post.save(function(err, post) { if (err) {return next(err); } res.json(comment); }) }); }) Here's my understanding.A POST method on the URL /posts/:post/comments is encounteredA new comment variable is created from the Comment prototypeThe comment.post object is set to the req.post value (Help needed: is this thanks to express and the URL parameters?)comment has a "save" method which is handed a function.this function brings in the (express or mongo) error and the "comment" (from the POST method?)this function errors out and quits if "err" existsthe function pushes the parameter "comment" onto the comments array of the req.post object (Question: is this in the browser memory?)req.post.save is ran, which pushes the data in memory to mongo (right?), bringing any errors and the post (Help needed: Why are we saving the post and not the comment)this function will quit if "err" existsres.json(comment) (Help needed: This part is the most puzzling. So the response already has a JSON method that hands data to the server?Seriously, thank you for your help!TL;DR; Don't understand how express uses REST to save to mongo. Extra reading material is appreciated.

Submitted January 18, 2016 at 12:08AM by urbanscouter

No comments:

Post a Comment