I’m working on a personal project and I’m working on user signup, one of the major things is having users with unique usernames and unique emails. So far I have it enforcing it on email, but for some reason it just will not do it for usernames either. It seems that when I put it in both areas it just overrides each other and allows for duplicates. Here is my model code:
const mongoose = require('mongoose');
const validator = require('validator');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const userSchema = new mongoose.Schema({
name: {
type: String,
unique: true,
required: true,
trim: true,
lowercase: true // Ensure lowercase for consistency
},
email: {
type: String,
unique: true,
required: true,
trim: true,
lowercase: true
},
password: {
type: String,
required: true,
minlength: 7,
validate(value) {
if (value.toLowerCase().includes('password')) {
throw new Error('Password cannot contain "password"');
}
}
},
characters: [{
character: {
type: String
}
}],
tokens: [{
token: {
type: String,
required: true
}
}],
groups: [{
group: {
type: String
}
}]
}, {
timestamps: true
});
userSchema.methods.generateAuthToken = async function () {
const user = this;
const token = jwt.sign({ _id: user._id.toString() }, process.env.JWT_SECRET);
user.tokens = user.tokens.concat({ token });
await user.save();
return token;
}
userSchema.methods.toJSON = function () {
const user = this;
const userObject = user.toObject();
delete userObject.password;
delete userObject.tokens;
return userObject;
}
userSchema.statics.findByCredentials = async (email, password) => {
const user = await User.findOne({ email });
if (!user) {
throw new Error('Unable to login...');
}
const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch) {
throw new Error('Unable to login...');
}
return user;
}
// Hash the plain text password before saving
userSchema.pre('save', async function (next) {
const user = this;
if (user.isModified('password')) {
user.password = await bcrypt.hash(user.password, 8);
}
next();
});
const User = mongoose.model('User', userSchema);
module.exports = User;
Any help would be appreciated!