【问题标题】:referenceerror: cannot access 'user' before initialization how to fix [duplicate]参考错误:初始化前无法访问“用户”如何修复[重复]
【发布时间】:2023-01-27 01:26:19
【问题描述】:

错误显示:referenceerror: cannot access 'user' before initialization ,我在调用 use 之后输入了密码,否则会出现错误,如 ***hashedPassword is not defiend *** 所以这就是为什么我在 bcrypt 之后调用但是时间显示错误,如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;

如何解决这个问题,

用户文件,这里我只创建后端。前端使用邮递员管理用户.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);

【问题讨论】:

  • 你能显示你从中导入用户的文件吗?

标签: node.js mongodb bcrypt


【解决方案1】:

您将本地范围内的用户重新定义为您刚刚创建的新用户。如果您更改行:

const user = await newuser.save();

到:

const userInstance = await newuser.save();

然后代码将运行。

你不应该重复使用来自更高范围的变量名。我建议调用 user import userModel 来避免这种情况。当您有 newUser、user 等并且它们都是对不同类型对象的引用时,它会变得非常混乱。使用诸如“userModel”、“userInstance”和“newUserInstance”之类的名称可以使您的代码更加明确。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-29
    • 2019-03-07
    • 1970-01-01
    • 2020-07-11
    • 1970-01-01
    • 1970-01-01
    • 2020-08-25
    • 2020-09-08
    相关资源
    最近更新 更多