Skip to content

Instantly share code, notes, and snippets.

@donjosef donjosef/posts.js
Last active Sep 24, 2019

Embed
What would you like to do?
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
You can’t perform that action at this time.