我設法讓我的用戶更新自己的個人資料,但我在一個問題去:當我的用戶想改變自己的用戶名,我面臨兩個問題:檢查用戶名是否不在數據庫中?
- 如果我的用戶想要改變在數據庫中的現有用戶名,它將對現有的用戶名(而不是用戶的電流)
- 當需要的用戶名在數據庫中不existe,它不會更新更新,因爲沒有現有的用戶名
這裏是我的代碼來獲取所有其他領域的工作,但用戶名的一個...
exports.update = function(req,res){
req.checkBody('username', 'Email is required').notEmpty().isEmail();
req.checkBody('password', 'Password is required').notEmpty();
req.checkBody('name', 'Name is required').notEmpty();
req.checkBody('surname', 'Surname is required').notEmpty();
req.checkBody('codePostal', 'Code postal is required').notEmpty();
req.checkBody('phoneNumber', 'Téléphone is required').notEmpty();
req.checkBody('address', 'Address is required').notEmpty();
req.checkBody('town', 'Town is required').notEmpty();
var errors = req.validationErrors();
console.log(errors);
if (errors) {
res.status(400).send(errors);
return;
}
var salt = bcrypt.genSaltSync(10),
hash = bcrypt.hashSync(req.body.password, salt);
User.findOne({ username: req.body.username }, function(err, user) {
if (err) {
return res.status(400).send('Error updating account.');
}
user.username = req.body.username;
user.password = hash;
user.name = req.body.name;
user.surname = req.body.surname;
user.codePostal = req.body.codePostal;
user.phoneNumber = req.body.phoneNumber;
user.address = req.body.address;
user.town = req.body.town
user.save(function(err) {
if (err) {
console.log(err);
res.status(500).send('Error updating account.');
return;
}
res.status(200).send('Account updated.');
});
});
}
由
userRoute = require('./server/api/user/index');
app.post('/account/update', authorizeRequest, userRoute.update);
function authorizeRequest(req, res, next) {
if (req.isAuthenticated()) {
next();
} else {
res.status(401).send('Unauthorized. Please login.');
}
}
我已經嘗試嵌套請求隨之而來的,但它只是不工作...: -/
我的用戶名現場已經是獨一無二的,你不能使用相同的用戶名已經創建一個帳戶! – antoine2vey