Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

A friend and I are trying to figure out exactly what is going on in this code that a tutorial produced. We are concerned about the flow of the client/server is once 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);
    });
});

Here is a gist just in-case people prefer it: https://gist.github.com/drknow42/fe1f46e272a785f8aa75

What we think we understand:

  1. factory.js sends a put request to the server
  2. expressRouter.js looks for the put request and finds that there is a route and calls the post.upvote method from MongoosePost.js (How does it know what post to use? and is req the body?)
  3. Mongoose executes adds 1 upvote to the post being sent and then executes the callback found in expressRouter.js

We don't understand what res.json(post) does and again, we don't understand how it knows what post to actually look at.

like image 746
Colby Hunter Avatar asked May 06 '15 05:05

Colby Hunter


1 Answers

It's some basic rules of RESTful services. Default restful route is:

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 a model, you are sending request to /model/:id. Based on id from request, it will find a model, which to update. In your case, id is :post in url. The body of request is contain the new/updated fields for this model. res.json() is sending newer version on model to your client-side angular.js code.

like image 168
vanadium23 Avatar answered Oct 20 '22 20:10

vanadium23