When I create a new user I want to access my user's role name and update.
If client is redirected with '/company/register' route my user role name will be 'company' by default if the client is redirected with '/user/register' user role name it will be guest or etc. I am new for MongoDB and NodeJS maybe my perspective totally wrong I am open to suggestion
const UserSchema = new Schema({
email:{
type: String,
required: true,
default: ""
},
encrypted_password:{
type:String,
required:true,
default: ""
},
user_role:[
{
role_name:{
type:String
},
is_company:{
type:Boolean,
default:false
},
write:{
type:Boolean,
default:false
},
read:{
type:Boolean,
default:false
},
publish:{
type:Boolean,
default:false
}
}
],
company:[
{
company_name:{
type:String
},
address:{
type:String
}
}
],
});
My register route
router.post('/register', (req, res) => {
User.findOne({email: req.body.email})
.then(company => {
if (company) {
return res.status(400).json({
email: 'Email already exists'
});
}
else {
const newUser = new User({
// I want to access here
email: req.body.email,
encrypted_password: req.body.encrypted_password,
updated_at: Date.now()
});
bcrypt.genSalt(10, (err, salt) =>{bcrypt.hash(newUser.encrypted_password, salt, (err, hash) => {newUser.encrypted_password = hash;
// New user added
newUser
.save()
.then(user => res.json(user))
.catch(err => console.log(err));
})
})
}
});
});
I already tried this, of course, it doesn't work
const newUser = new User({
email: req.body.email,
encrypted_password: req.body.encrypted_password,
user_role.role_name: "company",
updated_at: Date.now()
});
Use this method
const company_user_role = {role_name:"company",is_company:true};
const newUser = new User({
email: req.body.email,
encrypted_password: req.body.encrypted_password,
user_role: company_user_role,
updated_at: Date.now()
});