Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cannot access 'user' before initialization

I am new in Mern development, and getting this "Cannot access ‘user’ before initialization" error in controller file

Controller/user.js

const user = require('../models/user')
exports.signup = (req,res)=>{
   console.log('req.body', req.body);
  const user = new user(req.body);
  user.save((err, user)=>{    
if(err){
    return res.status(400).json({
        err
    })
}
res.json({
    user
})
  })
}

Route/user.js

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

const {signup} = require('../controllers/user');

router.post("/signup", signup);
module.exports = router;

>Solution :

On line 1 you define a variable named user.

On line 4 you defined a different variable named user in a different scope.

On line 4 you try to call the value of that variable as a function, but it doesn’t have a value yet.

You intended to call the function in the variable from line 1, but since the one on line 4 shadows it, you are calling that instead.

Don’t shadow your variables.

Change the name of one of them.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading