Skip to content

Instantly share code, notes, and snippets.

@pip-pipo
Created February 27, 2021 15:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pip-pipo/3951bbc8ac11cebb6324ed322be8fa98 to your computer and use it in GitHub Desktop.
Save pip-pipo/3951bbc8ac11cebb6324ed322be8fa98 to your computer and use it in GitHub Desktop.
Mern_stack_Rest_Api_Logic
import post from "../models/PostModel.js";
// get all post
export const getPost = async (req, res) => {
try {
await post.find((error, data) => {
if (error) {
console.log(error);
} else {
// console.log(data);
res.status(200).json(data);
}
});
} catch (err) {
return err;
}
};
// createPost
export const createPost = async (req, res) => {
const { name, message } = req.body;
try {
const dataPost = await new post({ name, message });
dataPost.save();
res.status(201).json({ mesg: "post created successfully" });
} catch (err) {
console.log(err);
}
};
// get Single Post
export const singlePost = async (req, res) => {
const { id } = req.params;
try {
const postupdate = await post.findById(id);
res.status(200).json(postupdate);
} catch (error) {
res.status(404).json({ message: error.message });
}
};
// update Post
export const updatePost = async (req, res) => {
const { name, message } = req.body;
const { id } = req.params;
try {
if (!mongoose.Types.ObjectId.isValid(id))
return res.status(404).send(`No post with id: ${id}`);
const updatePost = { name, message };
await post.findByIdAndUpdate(id, updatePost, { new: true });
res.json(updatePost);
} catch (err) {
res.status(404).json({ message: err.message });
r;
}
};
// deletePost
export const deletePost = async (req, res) => {
const { id } = req.params;
try {
await post.findByIdAndDelete(id);
res.json({ message: "Post deleted successfully" });
} catch (err) {
res.status(404).json({ message: error.message });
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment