How does a query request work through Angular, Express and Mongoose?

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.

+6
source share
1 answer

These are some basic RESTful rules. Default:

 Verb Path Description GET /post Get all posts GET /post/create Page where you can create post POST /post Method to create post in DB GET /post/:post Show post by id GET /post/:post/edit Page where you can edit post PUT/PATCH /post/:post Method to update post in DB DELETE /post/:post Method to delete post in DB 

When you need to update the model, you send a request to / model /: id. Based on the identifier from the request, he will find the model that will be updated. In your case id: post in url. The request body contains new / updated fields for this model. res.json() sends a newer version of the model to your angular.js client code.

+1
source

Source: https://habr.com/ru/post/986628/


All Articles