1

I try to create category to eCommerce project then it throws an error Postman - throws an error

These are source codes

location: ecommerce-backend\index.js

    const express = require('express')
    const env = require('dotenv')
    const app = express()
    const mongoose = require('mongoose')


    //routes
    const authRoutes = require('./routes/auth')
    const adminRoutes = require('./routes/admin/auth')
    const categoryRoutes = require('./routes/category')
    const productRoutes = require('./routes/product')
    const cartRoutes = require('./routes/cart')
    //environment variable or you can say constants
    env.config()

    //mongodb connection
    mongoose.connect(
        `mongodb+srv://${process.env.MONGO_DB_USERS}:${process.env.MONGO_DB_PASSWORD}@cluster0.nglbc.mongodb.net/${process.env.MONGO_DB_DATABASE}?retryWrites=true&w=majority`, 
        {
            useNewUrlParser: true, 
            useUnifiedTopology: true,
            useCreateIndex: true
        }
    ).then(() => {
        console.log('Database connected')
    });

    app.use(express.json())
    app.use('/api', authRoutes)
    app.use('/api', adminRoutes)
    app.use('/api', categoryRoutes)
    app.use('/api', cartRoutes)
    app.use('/api', productRoutes)

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

location: ecommerce-backend\routes\category.js

    const express = require('express')
    const { requireSignin, adminMiddleware } = require('../common-middleware')
    const { addCategory,getCategories } = require('../controller/category')
    const router = express.Router()
    const path = require('path')
    const shortid = require('shortid')
    const multer = require('multer')

    const storage = multer.diskStorage({
        destination: function (req, file, cb) {
          cb(null, path.join(path.dirname(__dirname), 'uploads'))
        },
        filename: function (req, file, cb) {
          cb(null, shortid.generate() + '-' + file.originalname)
        }
      })

    const upload = multer({ storage })

    router.post('/category/create',requireSignin, adminMiddleware,upload.single('categoryImage'), addCategory)
    router.get('/category/getcategory', getCategories)

    module.exports = router

location: ecommerce-backend\models\category.js

    const mongoose = require('mongoose')
    const categorySchema = new mongoose.Schema({

        name: {
            type: String,
            required: true,
            trim: true
        },
        slug: {
            type: String,
            required: true,
            unique: true
        },
        categoryImage: {
            type: String,
        },
        parentId: {
            type: String
        }

    }, { timestamps: true})

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

location: ecommerce-backend\controller\category.js

const Category = require('../models/category')
const slugify = require('slugify')

function createCategories(categories, parentId = null){

    const categoryList = []
    let category
    if(parentId == null){
        category = categories.filter(cat => cat.parentId == undefined)
    }else{
        category = categories.filter(cat => cat.parentId == parentId)
    }

    for(let cate of category){
        categoryList.push({
            _id: cate._id,
            name: cate.name,
            slug: cate.slug,
            children: createCategories(categories,cate._id)
        })
    }

    return categoryList
}

exports.addCategory = (req, res) => {

    const categoryObj = {
        name: req.body.name,
        slug: slugify(req.body.name)
    }

    if(req.file){
            categoryObj.categoryImage = process.env.API + '/public/'+ req.file.filename
    }

    if(req.body.parentId){
        categoryObj.parentId = req.body.parentId
    }

    const cat = new Category(categoryObj)
    cat.save((error,category) => {
        if(error) return res.status(400).json({ error})
        if(category){
            return res.status(201).json({ category})
        }
    })
}

exports.getCategories = (req,res) => {
    Category.find({})
    .exec((error, categories) => {
        if(error) return res.status(400).json({error})

        if(categories){

            const categoryList = createCategories(categories)

            res.status(200).json({categoryList})
        }
    })
}

this is my .env file at ecommerce-backend\ .env

PORT = 2000
MONGO_DB_USERS = mrzombit
MONGO_DB_PASSWORD = ********
MONGO_DB_DATABASE = ecommerce
JWT_SECRET = MERNSECRET
API = http://localhost:2000

I face this problem then I can't figure it out what happened to my code Thank you!

K SNP
  • 15
  • 1
  • 4

6 Answers6

1

You can also try with the following code which I hope would work for you.

**slug: slugify(toString(req.body.name))**
Rohit416
  • 3,416
  • 3
  • 24
  • 41
0

Make sure you have change the 'Content-Type' in postman header section.

Content-Type: multipart/form-data; boundary=<calculated when request is sent>
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
0

I just do below steps:

  1. Delete slugify package from package.json

  2. Reinstall slugify package : you will see that

    found 2 high severity vulnerabilities run npm audit fix to fix them, or npm audit for details

  3. Run npm audit fix

  4. Open new window ! in postman and copy the token from /api/admin/create and paste this token in the new window: /api/category/create in body ,

    form-data :

    name (doesn't exist in your DB yet)

    categoryImage (click file not text)

SEYED BABAK ASHRAFI
  • 4,093
  • 4
  • 22
  • 32
0

Add slug: { type: String, slug: "title"} to your model.

bpfrd
  • 945
  • 3
  • 11
0

I tried to debug the problem of slugify: string argument expected & found that in my case this object is comeing as {} so it was throwing slugify: string argument expected. try to find if all values are properly received in slugify method.

Code snippet

Schema.pre('save', (next)=> {
  console.log(`pre hook is triggered ${this.name}`.silly);
  // this.set({ updatedAt: new Date() });
  this.slug = slugify(this.name,{lower:true})
  next()
})
0

Check your routes again maybe one not work

  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community May 29 '23 at 13:03