From 8d687a57c0589b02ab3ea089668bc4a62b8306bd Mon Sep 17 00:00:00 2001 From: Amador Santiago Date: Wed, 28 Aug 2024 13:59:20 -0600 Subject: [PATCH 1/5] route for posts with methods --- apps/api/src/main.ts | 2 + apps/api/src/models/comment.ts | 7 ++ apps/api/src/models/post.ts | 10 +++ apps/api/src/routes/posts.ts | 160 +++++++++++++++++++++++++++++++++ 4 files changed, 179 insertions(+) create mode 100644 apps/api/src/models/comment.ts create mode 100644 apps/api/src/models/post.ts create mode 100644 apps/api/src/routes/posts.ts diff --git a/apps/api/src/main.ts b/apps/api/src/main.ts index 7f6b1e10..9862eaea 100644 --- a/apps/api/src/main.ts +++ b/apps/api/src/main.ts @@ -5,6 +5,7 @@ import helmet from 'helmet'; import { corsOptions } from './config/corsConfig'; import categories from './routes/categories'; +import posts from './routes/posts'; const host = process.env.HOST ?? 'localhost'; const port = process.env.PORT ? Number(process.env.PORT) : 3000; @@ -16,6 +17,7 @@ app.use(helmet()); app.use(cors(corsOptions)); app.use('/api/categories', categories); +app.use('/api/posts', posts); app.listen(port, host, () => { console.log(`[ ready ] http://${host}:${port}`); diff --git a/apps/api/src/models/comment.ts b/apps/api/src/models/comment.ts new file mode 100644 index 00000000..702027e8 --- /dev/null +++ b/apps/api/src/models/comment.ts @@ -0,0 +1,7 @@ +interface Comment { + id: string, + author: string, + content: string, +} + +export default Comment; \ No newline at end of file diff --git a/apps/api/src/models/post.ts b/apps/api/src/models/post.ts new file mode 100644 index 00000000..02a6bfa8 --- /dev/null +++ b/apps/api/src/models/post.ts @@ -0,0 +1,10 @@ +interface Post { + id: string, + title: string, + image: string, + description: string, + category: string, //string Id of the category + comments: string[], //array Array of comment ids +} + +export default Post \ No newline at end of file diff --git a/apps/api/src/routes/posts.ts b/apps/api/src/routes/posts.ts new file mode 100644 index 00000000..13a584a3 --- /dev/null +++ b/apps/api/src/routes/posts.ts @@ -0,0 +1,160 @@ +import express from 'express'; +import Post from '../models/post'; +import Comment from '../models/comment'; + +export const getPost = (id: string) => { + return posts.find((p) => p.id === id); +}; + +const router = express.Router(); +const posts:Post[] = []; +const comments:Comment[] = []; + +// get all posts +router.get('/', (req, res) => { + // Return an array of all the posts with status code 200 + res.status(200).json(posts); +}); + +// Get post by id +router.get('/:id', (req, res) => { + const { id } = req.params; + const post = getPost(id); + + if (!post) { + return res.status(404).json({ message: 'Ups, Post not found' }); + } + + // Return the post with a 200 status code + res.status(200).json(post); +}); + +// Get posts by category +router.get('/category/:category', (req, res) => { + const { category } = req.params; + const postsByCategory = posts.filter((post) => post.category == category ); + + if (postsByCategory.length == 0) { + return res.status(404).json({ message: 'Posts not found' }); + } + + // Return an array of all the posts by category with status code 200 + res.status(200).json(postsByCategory); +}); + +//create post +router.post('/', (req, res) => { + // Retrieve the name from the request body + const { title, image, description, category } = req.body; + + if (!title || !image || !description || !category) { + // If body values are empty or undefined return a 400 status code with a message + return res.status(400).json({ message: 'all fields are required.' }); + } + + // Generate a new post + const newPost = { + id: Date.now().toString(), + title: title, + image: image, + description: description, + category: category, + comments: [] + }; + // Add the new post to our array + posts.push(newPost); + + // Return the created post with a 201 status code + res.status(201).json(newPost); +}); + +//create post comment +router.post('/:id/comments', (req, res) => { + const { id } = req.params; + const { author, content } = req.body; + const post = getPost(id); + + if (!author || !content) { + // If body values are empty or undefined return a 400 status code with a message + return res.status(400).json({ message: 'all fields are required.' }); + } + + // Generate a new Comment + const newComment = { + id: Date.now().toString(), + author: author, + content: content, + }; + console.log(post) + comments.push(newComment); + post.comments.push(newComment.id); + + // Return the created comment with a 201 status code + res.status(201).json(newComment); +}); + +//delete post +router.delete('/:id', (req, res) => { + // Retrieve the id from the route params + const { id } = req.params; + // Retrieve the index of the Post in the array + const postIndex = posts.findIndex((p) => p.id === id); + + // "findIndex" will return -1 if there is no match + if (postIndex === -1) { + // If we don't find the Post return a 404 status code with a message + return res.status(404).json({ message: 'Post not found' }); + } + + // Remove the post from the array + posts.splice(postIndex, 1); + + // Return a 204 status code + res.status(204).send(); +}); + +//update post +router.patch('/:id', (req, res) => { + // Retrieve the id from the route params + const { id } = req.params; + const postIndex = posts.findIndex((p) => p.id === id); + + // "findIndex" will return -1 if there is no match + if (postIndex === -1) { + return res.status(404).json({ message: 'post not found' }); + } + + // Generate a copy of our post + const updatedPost = { ...posts[postIndex] }; + // Retrieve the name from the request body + const { title, image, description, category } = req.body; + + if (!title) { + // If body values are empty or undefined return a 400 status code with a message + return res.status(400).json({ message: 'title required.' }); + } + + // Check if we have a name, if so update the property + if (title) { + updatedPost.title = title; + } + if (image) { + updatedPost.image = image; + } + if (description) { + updatedPost.description = description; + } + if (category) { + updatedPost.category = category; + } + + + // Update the post in our array + posts[postIndex] = updatedPost; + + // Return the updated post with a 200 status code + res.status(200).json(updatedPost); +}); + + +export default router; \ No newline at end of file From 6c31b79483ed3ef2e0a0d0caf4d150dc2221a1f0 Mon Sep 17 00:00:00 2001 From: Amador Santiago Date: Thu, 12 Sep 2024 18:32:37 -0600 Subject: [PATCH 2/5] Refactor the code from last session to add a post controller --- apps/api/src/controllers/post.ts | 168 +++++++++++++++++++++++++++++++ apps/api/src/routes/posts.ts | 148 ++------------------------- 2 files changed, 176 insertions(+), 140 deletions(-) create mode 100644 apps/api/src/controllers/post.ts diff --git a/apps/api/src/controllers/post.ts b/apps/api/src/controllers/post.ts new file mode 100644 index 00000000..26584166 --- /dev/null +++ b/apps/api/src/controllers/post.ts @@ -0,0 +1,168 @@ +import Post from '../models/post'; +import Comment from '../models/comment'; + +const posts:Post[] = []; +const comments:Comment[] = []; + +export const getPost = (id: string) => { + return posts.find((p) => p.id === id); +}; + +//get all posts +const getPosts = (req, res) => { + res.status(200).json(posts); +} + +// Get post by id +const getPostById = (req, res) => { + const { id } = req.params; + const post = getPost(id); + + if (!post) { + return res.status(404).json({ message: 'Ups, Post not found' }); + } + + // Return the post with a 200 status code + res.status(200).json(post); +} + +// Get posts by category +const getPostsByCategory = (req, res) => { + const { category } = req.params; + const postsByCategory = posts.filter((post) => post.category == category ); + + if (postsByCategory.length == 0) { + return res.status(404).json({ message: 'Posts not found' }); + } + + // Return an array of all the posts by category with status code 200 + res.status(200).json(postsByCategory); +} + +//create post +const createPost = (req, res) => { + // Retrieve the name from the request body + const { title, image, description, category } = req.body; + + if (!title || !image || !description || !category) { + // If body values are empty or undefined return a 400 status code with a message + return res.status(400).json({ message: 'all fields are required.' }); + } + + // Generate a new post + const newPost = { + id: Date.now().toString(), + title: title, + image: image, + description: description, + category: category, + comments: [] + }; + // Add the new post to our array + posts.push(newPost); + + // Return the created post with a 201 status code + res.status(201).json(newPost); +}; + +//create post comment +const createComment = (req, res) => { + const { id } = req.params; + const { author, content } = req.body; + const post = getPost(id); + + if (!author || !content) { + // If body values are empty or undefined return a 400 status code with a message + return res.status(400).json({ message: 'all fields are required.' }); + } + + // Generate a new Comment + const newComment = { + id: Date.now().toString(), + author: author, + content: content, + }; + console.log(post) + comments.push(newComment); + post.comments.push(newComment.id); + + // Return the created comment with a 201 status code + res.status(201).json(newComment); +} + +//delete post +const deletePost = (req, res) => { + // Retrieve the id from the route params + const { id } = req.params; + // Retrieve the index of the Post in the array + const postIndex = posts.findIndex((p) => p.id === id); + + // "findIndex" will return -1 if there is no match + if (postIndex === -1) { + // If we don't find the Post return a 404 status code with a message + return res.status(404).json({ message: 'Post not found' }); + } + + // Remove the post from the array + posts.splice(postIndex, 1); + + // Return a 204 status code + res.status(204).send(); +}; + +//update post +const updatePost = (req, res) => { + // Retrieve the id from the route params + const { id } = req.params; + const postIndex = posts.findIndex((p) => p.id === id); + + // "findIndex" will return -1 if there is no match + if (postIndex === -1) { + return res.status(404).json({ message: 'post not found' }); + } + + // Generate a copy of our post + const updatedPost = { ...posts[postIndex] }; + // Retrieve the name from the request body + const { title, image, description, category } = req.body; + + if (!title) { + // If body values are empty or undefined return a 400 status code with a message + return res.status(400).json({ message: 'title required.' }); + } + + // Check if we have a name, if so update the property + if (title) { + updatedPost.title = title; + } + if (image) { + updatedPost.image = image; + } + if (description) { + updatedPost.description = description; + } + if (category) { + updatedPost.category = category; + } + + + // Update the post in our array + posts[postIndex] = updatedPost; + + // Return the updated post with a 200 status code + res.status(200).json(updatedPost); +}; + + +export default { + getPosts, + getPostById, + getPostsByCategory, + createPost, + createComment, + deletePost, + updatePost +} + + + diff --git a/apps/api/src/routes/posts.ts b/apps/api/src/routes/posts.ts index 13a584a3..f6307894 100644 --- a/apps/api/src/routes/posts.ts +++ b/apps/api/src/routes/posts.ts @@ -1,160 +1,28 @@ import express from 'express'; -import Post from '../models/post'; -import Comment from '../models/comment'; - -export const getPost = (id: string) => { - return posts.find((p) => p.id === id); -}; +import postController from '../controllers/post' const router = express.Router(); -const posts:Post[] = []; -const comments:Comment[] = []; // get all posts -router.get('/', (req, res) => { - // Return an array of all the posts with status code 200 - res.status(200).json(posts); -}); +router.get('/', postController.getPosts ); // Get post by id -router.get('/:id', (req, res) => { - const { id } = req.params; - const post = getPost(id); - - if (!post) { - return res.status(404).json({ message: 'Ups, Post not found' }); - } - - // Return the post with a 200 status code - res.status(200).json(post); -}); +router.get('/:id', postController.getPostById); // Get posts by category -router.get('/category/:category', (req, res) => { - const { category } = req.params; - const postsByCategory = posts.filter((post) => post.category == category ); - - if (postsByCategory.length == 0) { - return res.status(404).json({ message: 'Posts not found' }); - } - - // Return an array of all the posts by category with status code 200 - res.status(200).json(postsByCategory); -}); +router.get('/category/:category', postController.getPostsByCategory ); //create post -router.post('/', (req, res) => { - // Retrieve the name from the request body - const { title, image, description, category } = req.body; - - if (!title || !image || !description || !category) { - // If body values are empty or undefined return a 400 status code with a message - return res.status(400).json({ message: 'all fields are required.' }); - } - - // Generate a new post - const newPost = { - id: Date.now().toString(), - title: title, - image: image, - description: description, - category: category, - comments: [] - }; - // Add the new post to our array - posts.push(newPost); - - // Return the created post with a 201 status code - res.status(201).json(newPost); -}); +router.post('/', postController.createPost ); //create post comment -router.post('/:id/comments', (req, res) => { - const { id } = req.params; - const { author, content } = req.body; - const post = getPost(id); - - if (!author || !content) { - // If body values are empty or undefined return a 400 status code with a message - return res.status(400).json({ message: 'all fields are required.' }); - } - - // Generate a new Comment - const newComment = { - id: Date.now().toString(), - author: author, - content: content, - }; - console.log(post) - comments.push(newComment); - post.comments.push(newComment.id); - - // Return the created comment with a 201 status code - res.status(201).json(newComment); -}); +router.post('/:id/comments', postController.createComment ); //delete post -router.delete('/:id', (req, res) => { - // Retrieve the id from the route params - const { id } = req.params; - // Retrieve the index of the Post in the array - const postIndex = posts.findIndex((p) => p.id === id); - - // "findIndex" will return -1 if there is no match - if (postIndex === -1) { - // If we don't find the Post return a 404 status code with a message - return res.status(404).json({ message: 'Post not found' }); - } - - // Remove the post from the array - posts.splice(postIndex, 1); - - // Return a 204 status code - res.status(204).send(); -}); +router.delete('/:id', postController.deletePost); //update post -router.patch('/:id', (req, res) => { - // Retrieve the id from the route params - const { id } = req.params; - const postIndex = posts.findIndex((p) => p.id === id); - - // "findIndex" will return -1 if there is no match - if (postIndex === -1) { - return res.status(404).json({ message: 'post not found' }); - } - - // Generate a copy of our post - const updatedPost = { ...posts[postIndex] }; - // Retrieve the name from the request body - const { title, image, description, category } = req.body; - - if (!title) { - // If body values are empty or undefined return a 400 status code with a message - return res.status(400).json({ message: 'title required.' }); - } - - // Check if we have a name, if so update the property - if (title) { - updatedPost.title = title; - } - if (image) { - updatedPost.image = image; - } - if (description) { - updatedPost.description = description; - } - if (category) { - updatedPost.category = category; - } - - - // Update the post in our array - posts[postIndex] = updatedPost; - - // Return the updated post with a 200 status code - res.status(200).json(updatedPost); -}); +router.patch('/:id', postController.updatePost ); export default router; \ No newline at end of file From 38a0355782d5fc25087d63707411ef9d6e7a62aa Mon Sep 17 00:00:00 2001 From: Amador Santiago Date: Tue, 17 Sep 2024 15:49:14 -0600 Subject: [PATCH 3/5] Merge branch 'node/session-04' into node/amador.santiago From d08e0e0a6dcd1e6dce34348836cedcb3bc50d3f9 Mon Sep 17 00:00:00 2001 From: Amador Santiago Date: Wed, 18 Sep 2024 12:26:34 -0600 Subject: [PATCH 4/5] connect to mongodb database, using mongoose --- apps/api/.env | 2 +- apps/api/src/controllers/post.ts | 213 +++++++++++++++---------------- apps/api/src/models/comment.ts | 29 ++++- apps/api/src/models/post.ts | 30 ++++- 4 files changed, 157 insertions(+), 117 deletions(-) diff --git a/apps/api/.env b/apps/api/.env index ecaf5a7c..8199b521 100644 --- a/apps/api/.env +++ b/apps/api/.env @@ -1,3 +1,3 @@ ACCESS_TOKEN_SECRET=[YOUR_ACCESS_TOKEN_SECRET_HERE] REFRESH_TOKEN_SECRET=[YOUR_REFRESH_TOKEN_SECRET_HERE] -MONGO_URL=[YOUR_MONGO_CONNECTION_STRING_HERE] \ No newline at end of file +MONGO_URL=mongodb+srv://amadorsantiago368:tUzsAwreloIyZo3Y@cluster0.sn2n1.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0 \ No newline at end of file diff --git a/apps/api/src/controllers/post.ts b/apps/api/src/controllers/post.ts index 26584166..30352f63 100644 --- a/apps/api/src/controllers/post.ts +++ b/apps/api/src/controllers/post.ts @@ -1,158 +1,149 @@ import Post from '../models/post'; import Comment from '../models/comment'; -const posts:Post[] = []; -const comments:Comment[] = []; - -export const getPost = (id: string) => { - return posts.find((p) => p.id === id); -}; - //get all posts -const getPosts = (req, res) => { +const getPosts = async (req, res) => { + try { + const posts = await Post.find(); res.status(200).json(posts); + } catch (error) { + const { message } = error; + res.status(500).json({ message }); + } } // Get post by id -const getPostById = (req, res) => { +const getPostById = async (req, res) => { const { id } = req.params; - const post = getPost(id); - - if (!post) { - return res.status(404).json({ message: 'Ups, Post not found' }); + + try { + // const post = await Post.findById(id).populate({ + // path: "Comment", + // options: {strictPopulate: false}, + // match: { post_id: id }, + // }); + const post = await Post.findById(id).populate('comments'); + + if (!post) { + return res.status(404).json({ message: 'Ups, Post not found' }); + } + // Return the post with a 200 status code + res.status(200).json(post); + } catch (error) { + const { message } = error; + res.status(500).json({ message }); } - - // Return the post with a 200 status code - res.status(200).json(post); } // Get posts by category -const getPostsByCategory = (req, res) => { +const getPostsByCategory = async (req, res) => { const { category } = req.params; - const postsByCategory = posts.filter((post) => post.category == category ); - - if (postsByCategory.length == 0) { - return res.status(404).json({ message: 'Posts not found' }); - } - - // Return an array of all the posts by category with status code 200 - res.status(200).json(postsByCategory); + // const postsByCategory = posts.filter((post) => post.category == category ); + + try { + const posts = await Post.find({category: category}); + console.log(posts) + res.status(200).json(posts); + } catch (error) { + const { message } = error; + res.status(500).json({ message }); + } } //create post -const createPost = (req, res) => { +const createPost = async (req, res) => { // Retrieve the name from the request body const { title, image, description, category } = req.body; - if (!title || !image || !description || !category) { + /*if (!title || !image || !description || !category) { // If body values are empty or undefined return a 400 status code with a message return res.status(400).json({ message: 'all fields are required.' }); - } + }*/ // Generate a new post const newPost = { - id: Date.now().toString(), + // id: Date.now().toString(), title: title, image: image, description: description, category: category, comments: [] }; - // Add the new post to our array - posts.push(newPost); - - // Return the created post with a 201 status code - res.status(201).json(newPost); + + try { + const post = await Post.create(newPost); + // Return the created post with a 201 status code + res.status(201).json(post); + } catch (error) { + const { message } = error; + res.status(500).json({ message }); + } + }; + //create post comment -const createComment = (req, res) => { +const createComment = async (req, res) => { const { id } = req.params; - const { author, content } = req.body; - const post = getPost(id); - - if (!author || !content) { - // If body values are empty or undefined return a 400 status code with a message - return res.status(400).json({ message: 'all fields are required.' }); + const { author, content} = req.body; + try { + const newComment = { + author: author, + content: content, + post_id: id, + } + const comment = await Comment.create( + newComment + ); + //Post.findOne({_id : id }).populate({path: 'comments'}); + // Return the created comment with a 201 status code + res.status(201).json(comment); + } catch (error) { + const { message } = error; + res.status(500).json({ message }); } - - // Generate a new Comment - const newComment = { - id: Date.now().toString(), - author: author, - content: content, - }; - console.log(post) - comments.push(newComment); - post.comments.push(newComment.id); - - // Return the created comment with a 201 status code - res.status(201).json(newComment); } -//delete post -const deletePost = (req, res) => { - // Retrieve the id from the route params - const { id } = req.params; - // Retrieve the index of the Post in the array - const postIndex = posts.findIndex((p) => p.id === id); - - // "findIndex" will return -1 if there is no match - if (postIndex === -1) { - // If we don't find the Post return a 404 status code with a message - return res.status(404).json({ message: 'Post not found' }); - } - - // Remove the post from the array - posts.splice(postIndex, 1); - - // Return a 204 status code - res.status(204).send(); -}; - //update post -const updatePost = (req, res) => { - // Retrieve the id from the route params - const { id } = req.params; - const postIndex = posts.findIndex((p) => p.id === id); - - // "findIndex" will return -1 if there is no match - if (postIndex === -1) { +const updatePost = async (req, res) => { + // Retrieve the id from the route params + const { id } = req.params; + + try { + const post = await Post.findByIdAndUpdate(id, req.body, {new: true}) + + if (!post) { return res.status(404).json({ message: 'post not found' }); } - - // Generate a copy of our post - const updatedPost = { ...posts[postIndex] }; - // Retrieve the name from the request body - const { title, image, description, category } = req.body; - - if (!title) { - // If body values are empty or undefined return a 400 status code with a message - return res.status(400).json({ message: 'title required.' }); - } - - // Check if we have a name, if so update the property - if (title) { - updatedPost.title = title; - } - if (image) { - updatedPost.image = image; - } - if (description) { - updatedPost.description = description; - } - if (category) { - updatedPost.category = category; - } - - - // Update the post in our array - posts[postIndex] = updatedPost; - + // Return the updated post with a 200 status code - res.status(200).json(updatedPost); + res.status(200).json(post); + } catch (error) { + const { message } = error; + res.status(500).json({ message }); + } }; +//delete post +const deletePost = async (req, res) => { + // Retrieve the id from the route params + const { id } = req.params; + + try { + const post = await Post.findByIdAndDelete(id); + // If we don't find the post return a 404 status code with a message + if (!post) { + return res.status(404).json({ message: 'Post not found' }); + } + // Return a 200 status code + res.status(200).json(post); + } catch (error) { + const { message } = error; + res.status(500).json({ message }); + } + + +}; export default { getPosts, diff --git a/apps/api/src/models/comment.ts b/apps/api/src/models/comment.ts index 702027e8..5cf2d66d 100644 --- a/apps/api/src/models/comment.ts +++ b/apps/api/src/models/comment.ts @@ -1,7 +1,30 @@ -interface Comment { - id: string, +import mongoose, { Document, Schema } from 'mongoose'; + +/*interface IComment extends Document { author: string, content: string, -} +}*/ + +export const commentSchema = new Schema( + { + author: { + type: String, + required: [true, 'Property is required'] + }, + content: { + type: String, + required: [true, 'Property is required'] + }, + post_id: { + type: mongoose.Types.ObjectId, required: true, ref: 'Post' + } + }, + { + timestamps: true + } +); + +const Comment = mongoose.model('Comment', commentSchema); + export default Comment; \ No newline at end of file diff --git a/apps/api/src/models/post.ts b/apps/api/src/models/post.ts index 02a6bfa8..5ee413ba 100644 --- a/apps/api/src/models/post.ts +++ b/apps/api/src/models/post.ts @@ -1,5 +1,7 @@ -interface Post { - id: string, +import mongoose, { Document, Schema } from 'mongoose'; + +interface IPost extends Document { + title: string, image: string, description: string, @@ -7,4 +9,28 @@ interface Post { comments: string[], //array Array of comment ids } +export const postSchema = new Schema ( + { + + title: { + type: String, + required: [true, 'Property is required'] + }, + image: { + type: String + }, + description: { + type: String + }, + category: { + type: String + }, + comments: { + type: [{ type: Schema.Types.ObjectId, ref: 'Comment' }] + } + } +); + +const Post = mongoose.model('Post', postSchema); + export default Post \ No newline at end of file From 62594a76bec8378250bcacaa0bbaac691c4cf9db Mon Sep 17 00:00:00 2001 From: Amador Santiago Date: Wed, 18 Sep 2024 13:12:30 -0600 Subject: [PATCH 5/5] some refactors --- apps/api/.env | 2 +- apps/api/src/controllers/post.ts | 5 +++-- apps/api/src/models/comment.ts | 7 +------ apps/api/src/models/post.ts | 13 ++----------- 4 files changed, 7 insertions(+), 20 deletions(-) diff --git a/apps/api/.env b/apps/api/.env index 8199b521..ecaf5a7c 100644 --- a/apps/api/.env +++ b/apps/api/.env @@ -1,3 +1,3 @@ ACCESS_TOKEN_SECRET=[YOUR_ACCESS_TOKEN_SECRET_HERE] REFRESH_TOKEN_SECRET=[YOUR_REFRESH_TOKEN_SECRET_HERE] -MONGO_URL=mongodb+srv://amadorsantiago368:tUzsAwreloIyZo3Y@cluster0.sn2n1.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0 \ No newline at end of file +MONGO_URL=[YOUR_MONGO_CONNECTION_STRING_HERE] \ No newline at end of file diff --git a/apps/api/src/controllers/post.ts b/apps/api/src/controllers/post.ts index 30352f63..13a1f129 100644 --- a/apps/api/src/controllers/post.ts +++ b/apps/api/src/controllers/post.ts @@ -22,7 +22,7 @@ const getPostById = async (req, res) => { // options: {strictPopulate: false}, // match: { post_id: id }, // }); - const post = await Post.findById(id).populate('comments'); + const post = (await Post.findById(id).populate('comments')); if (!post) { return res.status(404).json({ message: 'Ups, Post not found' }); @@ -95,7 +95,8 @@ const createComment = async (req, res) => { const comment = await Comment.create( newComment ); - //Post.findOne({_id : id }).populate({path: 'comments'}); + const posts = await Post.findById(id); + await Post.findByIdAndUpdate(id, {comments:[...posts.comments, comment._id]}); // Return the created comment with a 201 status code res.status(201).json(comment); } catch (error) { diff --git a/apps/api/src/models/comment.ts b/apps/api/src/models/comment.ts index 5cf2d66d..3ca3e347 100644 --- a/apps/api/src/models/comment.ts +++ b/apps/api/src/models/comment.ts @@ -1,9 +1,4 @@ -import mongoose, { Document, Schema } from 'mongoose'; - -/*interface IComment extends Document { - author: string, - content: string, -}*/ +import mongoose, { Schema } from 'mongoose'; export const commentSchema = new Schema( { diff --git a/apps/api/src/models/post.ts b/apps/api/src/models/post.ts index 5ee413ba..087a25e8 100644 --- a/apps/api/src/models/post.ts +++ b/apps/api/src/models/post.ts @@ -1,13 +1,4 @@ -import mongoose, { Document, Schema } from 'mongoose'; - -interface IPost extends Document { - - title: string, - image: string, - description: string, - category: string, //string Id of the category - comments: string[], //array Array of comment ids -} +import mongoose, { Schema } from 'mongoose'; export const postSchema = new Schema ( { @@ -23,7 +14,7 @@ export const postSchema = new Schema ( type: String }, category: { - type: String + type: mongoose.Types.ObjectId, required: true, ref: 'Category' }, comments: { type: [{ type: Schema.Types.ObjectId, ref: 'Comment' }]