My studentApi.js is as follows, router.param() is used to save code for repeating again and againt.
router.param('post', function (req, res, next, id) {
var query = Post.findById(id);
query.exec(function (err, post) {
if (err) { return next(err); }
if (!post) { return next(new Error('Can\'t find post')); }
req.post = post;
return next();
})
});
router.put('/posts/:post/upvote', function (req, res, next) {
res.post.upvote(function (err, post) {
if (err) { return next(err);}
});
});
In angular I am calling like
o.upvote = function (post) {
return $http.put('/studentapi/posts/' + post._id + '/upvote')
.success(function (data) {
alert("post voted");
post.upvotes += 1;
});
};
My model is as follows, calling upvote method internally from model.
var mongoose = require('mongoose');
var PostSchema = new mongoose.Schema({
title: String,
link: String,
upvotes: { type: Number, default: 0 },
downvotes: { type: Number, default: 0 },
comments: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Comment' }]
});
mongoose.model('Post', PostSchema);
PostSchema.methods.upvote = function (cb) {
this.upvotes += 1;
this.save(cb);
}