Home > Software design >  referenceerror: cannot access 'user' before initialization
referenceerror: cannot access 'user' before initialization

Time:06-11

error showing: referenceerror: cannot access 'user' before initialization , I encored the password, after I called use, or there is an error will come like ***hashedPassword is not defiend *** so this why I call after bcrypt but that time showing an error like, referenceerror: cannot access 'user' before initialization

auth.js

const router =require("express").Router();
const  user =require("../models/user");
const bcrypt =require("bcrypt")

//REGISTER
router.post("/register",async(req,res)=>{

  try{
 // generate new encorded password>>
    const salt = await bcrypt.genSalt(10);
    const hashedPassword =await bcrypt.hash(req.body.password, salt);
 // creat new user 
 const newuser =  new user({
        username:req.body.username,
        email:req.body.email,
        password:hashedPassword,
    })

// save user and respond in DB
    const user = await newuser.save();
    res.status(200).json(user)
  }catch(err){
    res.status(500).json(err)
  }
}) 
module.exports = router;

how to solve this,

user file, here I create only the back end. front end is managed using postman user.js

const mongoose = require("mongoose")
      
   const userSchema= new mongoose.Schema({
        username:{
            type:String,
            require:true,
            min:3,
            max:20,
            unique:true
        },
        email:{
            type:String,
            required:true,
            min:4,
            max:10,
            unique:true
        },
        password:{
            type:String,
            required:true,
            min:5,
         
        },
    profilePicture:{
        type:String,
        default:"",
    },
    coverPitcture:{
        type:String,
        default:"",
    },
    followers:{
        type:Array,
        default:[],
    },
    following:{
        type:Array,
        default:[],
    },
    isAdmin:{
        type:Boolean, 
        default:false,
    },
    description:{
       type:String,
       max:50,
    }, 
    city:{
        type:String,
        max:50,
    },
    from:{
        type:String,
        max:50,
    },
    relationShip:{
        type:Number,
        enum:[1,2,3],
    },
},
{timestamps:true}
);
module.exports = mongoose.model("user",userSchema);

CodePudding user response:

You redefine user in the local scope to the new user you just created. If you change the line:

const user = await newuser.save();

to:

const userInstance = await newuser.save();

then the code will run.

You should never re-use a variable name from a higher scope. I'd reccomend calling the user import userModel to avoid this. It becomes very confusing when you have newUser, user, etc. and they are all references to different types of objects. Using names like "userModel," "userInstance," and "newUserInstance" keeps your code more explicit.

  • Related