目前關於bootcamp&course資料的搜索與互動算是告一段落
接下來我們要建立使用者的資料,讓使用者能註冊、登入、與bootcamp&course資料互動等等
首先,需要先建立一筆新的user model
在'./models'建立新的User.js file
const UserSchema = new mongoose.Schema({
name: {
type: String,
required: [true, 'Please add a name']
},
email: {
type: String,
required: [true, 'Please add an email'],
unique: true,
match: [
/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/,
'Please add a valid email'
]
},
role: {
type: String,
enum: ['user', 'publisher'],
default: 'user'
},
password: {
type: String,
required: [true, 'Please add a password'],
minlength: 6,
select: false
},
建立完user model後,一樣在controllers新增auth.js
exports.register = asyncHandler(async (req, res, next) => {
const { name, email, password, role } = req.body;
// 新增user
const user = await User.create({
name,
email,
password,
role
});
res.status(200).json({ success: true });
});
比較特別的是,我們不希望使用者註冊的個人資料外洩,所以要將密碼加密
這邊會用到bcryptjs這個package
在儲存document前,hash使用者輸入的密碼,this refers to req.body
UserSchema.pre('save', async function(next) {
const salt = await bcrypt.genSalt(10);
this.password = await bcrypt.hash(this.password, salt);
});