錯誤顯示:referenceerror: cannot access 'user' before initialization , I encored the password, after I call 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;
如何解決這個問題,
用戶檔案,這里我只創建后端。前端使用郵遞員 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);
uj5u.com熱心網友回復:
您將本地范圍內的用戶重新定義為您剛剛創建的新用戶。如果換行:
const user = await newuser.save();
至:
const userInstance = await newuser.save();
然后代碼將運行。
你永遠不應該重復使用更高范圍的變數名。我建議呼叫用戶 import userModel 來避免這種情況。當您擁有 newUser、user 等時會變得非常混亂,并且它們都是對不同型別物件的參考。使用“userModel”、“userInstance”和“newUserInstance”之類的名稱可以讓您的代碼更加明確。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/489695.html
上一篇:MissingSchemaError:尚未為模型“用戶,userSchema”注冊架構。使用mongoose.model(name,schema)
