My friend and I are trying to figure out what exactly is happening in this code that the textbook prepared. We are concerned about the client / server flow when line 8 of factory.js is called:
factory.js
app.factory('postFactory', ['$http', function($http) { var o = { posts: [] }; o.upvote = function(post){ return $http.put('/posts/' + post._id + "/upvote").success(function(data){ post.upvotes += 1; }); }; return o; }]);
MongoosePost.js
var mongoose = require('mongoose'); var PostSchema = new mongoose.Schema({ title: String, url: String, upvotes: {type: Number, default: 0}, comments: [{type: mongoose.Schema.Types.ObjectId, ref: 'Comment' }] }); PostSchema.methods.upvote = function(cb) { this.upvotes += 1; this.save(cb); } mongoose.model('Post', PostSchema);
expressRouter.js
var express = require('express'); var router = express.Router(); var mongoose = require('mongoose'); var Post = mongoose.model('Post'); var Comment = mongoose.model('Comment'); router.put('/posts/:post/upvote', function(req, res, next) { req.post.upvote(function(err, post) { if(err) { return next(err); } console.log(post); res.json(post); }); });
The bottom line is that people prefer this: https://gist.github.com/drknow42/fe1f46e272a785f8aa75
In our opinion, we understand:
- factory.js sends a request request to the server
- expressRouter.js looks for the request request and finds that there is a route and calls the post.upvote method from MongoosePost.js (How does he know which post to use? and req body?)
- Mongoose performs adds 1 upvote to the message being sent, and then performs the callback found in expressRouter.js
We donβt understand what res.json (post) does again, we donβt understand how it knows which post to actually look at.
source share