Home > OS >  My app Crash due to some error in my node.js backend code which post the accesoies and slug into dat
My app Crash due to some error in my node.js backend code which post the accesoies and slug into dat

Time:09-20

Its my node.js backend code which put the accesory and slug into the database I dont know why my app crash

const express=require('express');
const Category = require("../models/Category");
const slugify=require('slugify');
const router=express.Router;



router.post('/addcategory',(req,res)=>{

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

 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});
    }
})




});

module.exports=router;

Its My Model schema code of mongodb I added it for your assistent

const mongoose = require('mongoose');
const { schema } = require('./User');
const { Schema } = mongoose;

const CategorySchema=new Schema({

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






});
const Category=mongoose.model('Category',CategorySchema);
module.exports=Category;

Its my index.js code

const connectToMongo=require('./db');
var cors = require('cors');
const express = require('express')

connectToMongo();
const app = express()
app.use(cors())
const port = 5000


app.use(express.json());
app.use('/api/authent',require('./routes/authent'))
app.use('/api/category1',require('./routes/category'))


app.listen(port, () => {
  console.log(`iNoteBook Backend listening on port ${port}`)
})

The error thro by the terminal is

C:\Users\Dell\Desktop\cinemaapp\backend\node_modules\express\lib\router\index.js:513 this.stack.push(layer); ^

TypeError: Cannot read properties of undefined (reading 'push') at Function.route (C:\Users\Dell\Desktop\cinemaapp\backend\node_modules\express\lib\router\index.js:513:14) at Function.proto. [as post] (C:\Users\Dell\Desktop\cinemaapp\backend\node_modules\express\lib\router\index.js:520:22) at Object. (C:\Users\Dell\Desktop\cinemaapp\backend\routes\category.js:8:8) at Module._compile (node:internal/modules/cjs/loader:1105:14) at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10) at Module.load (node:internal/modules/cjs/loader:981:32) at Function.Module._load (node:internal/modules/cjs/loader:822:12) at Module.require (node:internal/modules/cjs/loader:1005:19) at require (node:internal/modules/cjs/helpers:102:18) at Object. (C:\Users\Dell\Desktop\cinemaapp\backend\index.js:13:26) [nodemon] app crashed - waiting for file changes before starting...

CodePudding user response:

You're not creating a router properly, you need to call express.Router:

const router = express.Router();
  • Related