2015-05-06 12 views
6

Bir arkadaşım ve ben bir öğreticinin ürettiği bu kodda neler olduğunu tam olarak anlamaya çalışıyoruz.Bir istek isteği Angular, Express ve Mongoose ile nasıl çalışır?

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

: İstemcinin akışı endişe/sunucu kez hat factory.js 8 adı verilir İşte
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); 
    }); 
}); 

kişi bunu tercih sadece in-case özü de geçerli: https://gist.github.com/drknow42/fe1f46e272a785f8aa75

biz anlıyorum Ne:

  1. factory.js
  2. expressRouter.js koymak isteği arar sunucuya bir satım isteği gönderir ve bir rota olduğunu bulur ve yazı çağırır MongoosePost.js'den .upvote yöntemi ( , hangi gönderinin kullanılacağını nasıl biliyor? ve vücudu req edilir?)
  3. Gelincik yürütür ekler mesaja 1 upvote gönderiliyor ve daha sonra Biz neyi res.json (post anlamıyorum

expressRouter.js bulunan geri arama yürütür) yok ve yine, aslında hangi gönderinin baktığını nasıl bildiklerini anlamıyoruz.

cevap

1

RESTful hizmetlerinin bazı temel kuralları. Standart dinlendirici yoldur: id: Bir modeli güncellemek için gerektiğinde,/modele/isteği gönderiyor

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 

. İsteğinize göre, güncelleştirmek için bir model bulacaksınız. Durumunuzda, id: post in url. İstek gövdesi, bu model için yeni/güncellenmiş alanları içerir. res.json(), istemci tarafındaki angular.js koduna modelde daha yeni bir sürüm gönderiyor.

İlgili konular