Last active
September 24, 2019 19:15
-
-
Save donjosef/3a2aa4ebac83bcc959c26b9e3258d5ae to your computer and use it in GitHub Desktop.
Create controllers/middlewares
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const Post = require('../model.js'); //Our Model | |
module.exports = { | |
getPosts: (req, res, next) => { | |
//Find posts in posts collection | |
Post.find() | |
.then(posts => { | |
res.status(200).json({ message: 'Posts fetched!', posts }) | |
}) | |
.catch(err => console.log('Error while fetching posts', err)) | |
}, | |
createPost: (req, res, next) => { | |
const { title, content } = req.body; | |
//instantiate a new post object/document | |
const post = new Post({ | |
title, | |
content, | |
creator: { | |
name: 'Josef' | |
} | |
}); | |
//Now we can save the post in the database | |
post | |
.save() | |
.then(post => { | |
//Once is it stored in database, we can send the response | |
res.status(201).json({ | |
message: 'Post created successfully!', | |
post | |
}); | |
}) | |
.catch(err => console.log('Error while saving a new post', err)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment