CRUD – I’m not able to send a especific data to the database

I am trying to insert a category and it is not sending its ‘name’ to the database. On Postman and Robo Mongo I see that I sent ‘_id’, ‘createdAt’, ‘updatedAt’ and “_V” all correctly. But the ‘name’ is not sending. Does anyone know what’s going on? Thanks.

app.js

const express = require('express')
const mongoose = require('mongoose')
const morgan = require('morgan')
const bodyParser = require('body-parser') 
const cookieParser = require('cookie-parser')
const expressValidator = require('express-validator')  
require('dotenv').config()
//import routes
const authRoutes =  require('./routes/auth')
const userRoutes =  require('./routes/user')
const categoryRoutes =  require('./routes/category')

// app
const app = express()

// db
mongoose.connect(process.env.DATABASE, {
  useNewUrlParser: true,
  useCreateIndex: true
})
.then(() => console.log('DB Connected'))

// middlewares
app.use(morgan('dev'))
app.use(bodyParser.json())
app.use(cookieParser())
app.use(expressValidator())

// routes middleware
app.use('/api', categoryRoutes)

const port = process.env.PORT || 8000

app.listen(port, () => {
  console.log(`Server is running on port ${port}`)
})

controllers/category.js

const Category = require("../models/category")
const { errorHandler } = 
require("../helpers/dbErrorHandler")

exports.create = (req, res) => {
  const category = new Category(req.body)  
  category.save((err, data) => {   
    if(err) {
      return res.status(400).json({
        error: errorHandler(err)      
      })
    }
    res.json({ data })  
  })
}

routes/category

const express = require('express')
const router = express.Router()

const { create } = require('../controllers/category')
    
router.post('/category/create/:userId', create);

router.param("userId", userById)

module.exports = router

models/category

const mongoose = require('mongoose')

const categorySchema = new mongoose.Schema(
  {
    name: {
      type: String,
      trim: true,
      required: false,
      maxlength: 32
    }
  },
  { timestamps: true }
);

module.exports = mongoose.model('Category', categorySchema)

Answer

config the header request in postman like this enter image description here

and the body of request enter image description here

Leave a Reply

Your email address will not be published. Required fields are marked *