| 0 | kirasiris | Categories: Tags: ,

NodeJS

Well, another post regarding NodeJS and Mongoose.

This posts is just an example of how to create a simple CRUD system:

const express = require('express');
const router = express.Router();
const { check, validationResult } = require('express-validator/check');
const auth = require('../../../middleware/auth');
// Models
const Blog = require('../../../models/admin/Blog');
const User = require('../../../models/User');

// @route       GET api/admin/blogs
// @description Get all blog
// @access      Private - Admin Access
router.get('/', auth, async (req, res) => {
  try {
    const posts = await Blog.find().sort({ date: -1 });
    res.json(posts);
  } catch (err) {
    console.error(err.message);
    res.status(500).send('Server error');
  }
});

// @route       POST api/admin/blogs
// @description Create a blog
// @access      Private - Admin Access
router.post(
  '/',
  [
    auth,
    [
      check('title', 'Title is required')
        .not()
        .isEmpty(),
      check('text', 'Text is required')
        .not()
        .isEmpty()
    ]
  ],
  async (req, res) => {
    const errors = validationResult(req);

    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }

    try {
      const user = await User.findById(req.user.id).select('-password');

      const newPost = new Blog({
        user: req.user.id,
        title: req.body.title,
        slug: req.body.slug,
        post_image: req.body.post_image,
        text: req.body.text,
        term_id: req.body.term_id,
        commented: req.body.commented,
        featured: req.body.featured,
        status: req.body.status
      });

      const post = await newPost.save();
      res.json(post);
    } catch (err) {
      console.error(err.message);
      res.status(500).send('Server error');
    }
  }
);

// @route       GET api/blogs/:id
// @description Get blogs by :id
// @access      Private - Admin Access
router.get('/:id', auth, async (req, res) => {
  try {
    const post = await Blog.findById(req.params.id);

    if (!post) {
      return res.status(404).json({ msg: 'Blog not found' });
    }

    res.json(post);
  } catch (err) {
    console.error(err.message);
    if (err.kind === 'ObjectId') {
      return res.status(404).json({ msg: 'Blog not found' });
    }
    res.status(500).send('Server error');
  }
});

// @route       PUT api/admin/blogs
// @description Update blog
// @access      Private - Admin Access
router.put('/:id', [
  auth,
  [
    check('title', 'Title is required')
      .not()
      .isEmpty(),
    check('text', 'Text is required')
      .not()
      .isEmpty()
  ]
], async (req, res) => {

  const errors = validationResult(req);
  // Check for errors
  if (!errors.isEmpty()) {
    return res.status(400).json({ errors: errors.array() });
  }

  // Destructure
  const {
    title,
    slug,
    post_image,
    text,
    term_id,
    commented,
    featured,
    status
  } = req.body;

  // Build page object
  const pageFields = {};
  pageFields.user = req.user.id;
  title ? (pageFields.title = title) : (pageFields.title = null);
  slug ? (pageFields.slug = slug) : (pageFields.slug = null);
  post_image ? (pageFields.post_image = post_image) : (pageFields.post_image = null);
  text ? (pageFields.text = text) : (pageFields.text = null);
  term_id ? (pageFields.term_id = term_id) : (pageFields.term_id = null);
  commented ? (pageFields.commented = commented) : (pageFields.commented = null);
  featured ? (pageFields.featured = featured) : (pageFields.featured = null);
  status ? (pageFields.status = status) : (pageFields.status = null);

  try {

    const post = await Blog.findById(req.params.id);

    if (!post) {
      return res.status(404).json({ msg: 'Blog not found' });
    }

    await Blog.findByIdAndUpdate(req.params.id, pageFields, { new: true });

    // Return profile if found
    return res.json(post);

  } catch (err) {
    console.error(err.message);
    res.status(500).send('Server error');
  }
});

// @route       DELETE api/admin/blogs/:id
// @description Delete a blog
// @access      Private - Admin Access
router.delete('/:id', auth, async (req, res) => {
  try {
    const post = await Blog.findById(req.params.id);
    // Check post
    if (!post) {
      return res.status(404).json({ msg: 'Blog not found' });
    }

    await post.remove();
    res.json({ msg: 'Blog removed' });
  } catch (err) {
    console.error(err.message);
    if (err.kind === 'ObjectId') {
      return res.status(404).json({ msg: 'Blog not found' });
    }
    res.status(500).send('Server error');
  }
});

module.exports = router;

Remember, I’m using auth; if you don’t want to use it, just delete the second? parameter on each route.

Leave a Reply

Back to Top