0
我一直在从thinkster.io教程开发一个reddit克隆,我无法弄清楚如何将upvote值保存到数据库。有人可以看看吗?保存upvote值到数据库(MEAN stack - reddit clone)
从angularApp.js //
.factory('posts', ['$http', 'auth', function($http, auth){
var o = {
posts: []
};
o.upvote = function(post) {
return $http.put('/posts/' + post._id + '/upvote', {
headers: {Authorization: 'Bearer '+auth.getToken()}
}).success(function(data){
post.votes += 1;
});
};
return o;
}])
.controller('MainCtrl', [
'$scope',
'posts',
'auth',
function($scope, posts, auth){
$scope.posts = posts.posts;
$scope.isLoggedIn = auth.isLoggedIn;
$scope.addPost = function(){
//prevents empty posts
if(($scope.title === '') || ($scope.body === '')) { return; }
//creates post
posts.create({
title: $scope.title,
votes: 0,
createdOn: Date.now(),
link: $scope.link,
body: $scope.body,
});
//returns empty values after post is created
$scope.title = '';
$scope.link = '';
$scope.body = '';
};
$scope.incrementUpvotes = function(post){
posts.upvote(post);
};
}])
//猫鼬交架构
var PostSchema = new mongoose.Schema({
title: { type: String, required: '{PATH} is required!'},
body: String,
createdOn: { type: Date, default: Date.now },
votes: {type: Number, default: 0},
comments: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Comment' }],
author: String
});
PostSchema.methods.upvote = function(cb) {
this.votes += 1;
this.save(cb);
};
mongoose.model('Post', PostSchema);
//从index.js
// upvote a post
router.put('/posts/:post/upvote', auth, function(req, res, next) {
req.post.upvote(function(err, comment){
if (err) { return next(err); }
res.json(comment);
});
});
从index.ejs //(HTML )
<i ng-click="incrementUpvotes(post)" class="ion-chevron-up"></i><br>
{{comment.votes}}<br>
你有什么问题?我可以看到有2个不同的网址,这可能是问题吗?一个是“/ posts//upvote”,另一个是“/ posts//comments//upvote”。 –
MrWillihog
我不小心粘贴了错误的代码位。我刚刚更新了它。 –
你有什么问题?你有错误吗? – MrWillihog