I'm currently facing an issue while trying to register a new user through my Angular app. Even though I've set the name field as unique in Mongo, when I attempt to register a user with an existing username, it allows me to do so without returning an error. This results in multiple users with the same name in the database.
Here's a snippet of the API:
apiRoutes.post('/signup', function(req, res) {
if (!req.body.userId || !req.body.password) {
res.json({success: false, msg: 'Please pass name and password.'});
} else {
var newUser = new User({
name: req.body.name,
password: req.body.password,
wallet: req.body.wallet,
userPic: req.body.userPic
});
// save the user
newUser.save(function(err) {
if (err) {
return res.json({success: false, msg: 'Username already exists.'});
}
res.json({success: true, msg: 'Successful created new user.'});
});
}
});
Below is the model code:
// set up a mongoose model
var UserSchema = new Schema({
name: {
type: String,
unique: true,
required: true
},
password: {
type: String,
required: true
},
wallet: {
type: Number,
required: true
},
userPic: {
type: String,
required: true,
unique: true
}
});
Lastly, here's the POST request code where user login and password are obtained from external sources:
let newUser = {
password: password,
wallet: 0,
userPic: md5(login),
name: login
};
this.$http.post('http://127.0.0.1:8080/api' + '/signup', newUser);