Advertisement
Guest User

Untitled

a guest
Jul 19th, 2017
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.57 KB | None | 0 0
  1. let mongoose = require("mongoose");
  2. let Schema = mongoose.Schema;
  3.  
  4. let PostSchema = Schema({
  5. title: {type: String},
  6. body: {type: String},
  7. date: {type: Date},
  8. tags:[{type: String}],
  9. _author: {type: Schema.Types.ObjectId, ref: 'author'}
  10. });
  11.  
  12. let AuthorSchema = Schema({
  13. name: {type: String},
  14. photo: {type: String},
  15. bio: {type: String},
  16. username: {type: String, index: true},
  17. posts:[{type: Schema.Types.ObjectId, ref: 'post'}],
  18. password: {type: String}
  19. });
  20.  
  21. let Author = mongoose.model('author', AuthorSchema);
  22. let Post = mongoose.model('post', PostSchema);
  23.  
  24. module.exports = Author;
  25. module.exports = Post;
  26.  
  27. module.exports.createAuthor = (newAuthor, callback)=>{
  28. newAuthor.save(callback)
  29. };
  30.  
  31. module.exports.createPost = (username, newPost, callback)=>{
  32. Author.findOne({username:username}).then((author)=>{
  33. newPost._author = author._id
  34. author.posts.push(newPost);
  35. newPost.save().then(err, auth)=>{
  36. author.save(callback);
  37. };
  38. },(err)=>{
  39. if(err)
  40. throw err;
  41. });
  42. };
  43.  
  44. module.exports.getAuthorByPostTitle = (postTitle, callback)=>{
  45. Post.findOne({title:postTitle}).populate('_author').exec((err, post)=>{
  46. if(err)
  47. throw err;
  48. else
  49. return post._author;
  50. });
  51. };
  52.  
  53. module.exports.getPostsByAuthorId = (authorId, callback)=>{
  54. Post.find({_author:authorId}).exec((err, posts)=>{
  55. if(err)
  56. throw err;
  57. else
  58. return posts;
  59. });
  60. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement