-
Notifications
You must be signed in to change notification settings - Fork 0
/
postprovider.js
80 lines (69 loc) · 1.65 KB
/
postprovider.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/my_blog');
var Schema = mongoose.Schema
, ObjectId = Schema.ObjectId;
var Comments = new Schema({
person : String
, comment : String
, created_at : Date
});
var Post = new Schema({
author : ObjectId
, title : String
, body : String
, created_at : Date
, comments : [Comments]
});
mongoose.model('Post', Post);
var Post = mongoose.model('Post');
PostProvider = function(){};
//Find all posts
PostProvider.prototype.findAll = function(callback) {
Post.find({}, function (err, posts) {
callback( null, posts )
});
};
//Find post by ID
PostProvider.prototype.findById = function(id, callback) {
Post.findById(id, function (err, post) {
if (!err) {
callback(null, post);
}
});
};
//Update post by ID
PostProvider.prototype.updateById = function(id, body, callback) {
Post.findById(id, function (err, post) {
if (!err) {
post.title = body.title;
post.body = body.body;
post.save(function (err) {
callback();
});
}
});
};
//Create a new post
PostProvider.prototype.save = function(params, callback) {
var post = new Post({title: params['title'], body: params['body'], created_at: new Date()});
post.save(function (err) {
callback();
});
};
//Add comment to post
PostProvider.prototype.addCommentToPost = function(postId, comment, callback) {
this.findById(postId, function(error, post) {
if(error){
callback(error)
}
else {
post.comments.push(comment);
post.save(function (err) {
if(!err){
callback();
}
});
}
});
};
exports.PostProvider = PostProvider;