Advertisement
Guest User

Untitled

a guest
Feb 19th, 2020
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // z Post.js
  2. postSchema.virtual("comments", {
  3.   ref: "Comment",
  4.   localField: "_id",
  5.   foreignField: "author"
  6. });
  7.  
  8. //Comment.js
  9. const mongoose = require("mongoose");
  10.  
  11. const commentSchema = mongoose.Schema(
  12.   {
  13.     commentedPostId: {
  14.       type: mongoose.Schema.Types.ObjectId,
  15.       ref: "Post",
  16.       required: true
  17.     },
  18.     image: {
  19.       type: Buffer
  20.     },
  21.     author: {
  22.       type: mongoose.Schema.Types.ObjectId,
  23.       ref: "User",
  24.       required: true
  25.     },
  26.     body: {
  27.       type: String
  28.     }
  29.   },
  30.   {
  31.     timestamps: true
  32.   }
  33. );
  34.  
  35. const Comment = mongoose.model("Comment", commentSchema);
  36.  
  37. module.exports = Comment;
  38.  
  39. // z kontrolera post.js
  40. const { id } = req.params;
  41.     const post = await Post.findById(id);
  42.     await post.populate("comments").execPopulate();
  43.  
  44.     res.status(200).send({
  45.       post,
  46.       comments: post.comments
  47.     });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement