Skip to content

Instantly share code, notes, and snippets.

@donjosef
Last active September 24, 2019 19:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save donjosef/3a2aa4ebac83bcc959c26b9e3258d5ae to your computer and use it in GitHub Desktop.
Save donjosef/3a2aa4ebac83bcc959c26b9e3258d5ae to your computer and use it in GitHub Desktop.
Create controllers/middlewares
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