I have a schema and i want the username field to be unique but it's not working (The "required" works normally). What i did try: restart mongodb, drop database. May i know what i am missing ?
Here is my schema:
import mongoose, { HookNextFunction, model } from 'mongoose';
import bcrypt from 'bcrypt';
import { AdminDocument } from '../interfaces';
const AdminSchema = new mongoose.Schema(
{
username: { type: String, unique: true, required: true },
email: { type: String, unique: true, required: true },
password: { type: String, required: true },
role: { type: Number, enum: [0, 1], required: true },
address: { type: String },
phone: { type: String, required: true },
photo: { type: String, default: null },
name: { type: String, required: true },
gender: { type: Number, enum: [0, 1, 2], required: true },
refreshToken: { type: String, default: null },
},
{ timestamps: true }
);
AdminSchema.pre('save', async function (next: HookNextFunction) {
let user = this as AdminDocument;
if (!user.isModified('password')) {
return next();
}
const salt = await bcrypt.genSalt(Number(process.env.SALT_WORK_FACTOR));
const hashedPassword = await bcrypt.hash(user.password, salt);
user.password = hashedPassword;
return next();
});
AdminSchema.methods.comparePassword = async function (
candidatePassword: string
) {
const user = this as AdminDocument;
const isValid = await bcrypt.compare(candidatePassword, user.password);
return isValid;
};
export default model<AdminDocument>('Admin', AdminSchema);
CodePudding user response:
In Mongoose connection script enable these options useCreateIndex
and autoIndex
to become true.
mongoose
.connect('connection url', {
useUnifiedTopology: true,
useNewUrlParser: true,
useCreateIndex: true, //make this true
autoIndex: true, //make this also true
})
.then(() => {
console.log('Connected to mongoDB');
});
then drop the schemas from your db.
CodePudding user response:
I have solved this by creating an index using mongodb compass. But the problem is that i can not use the schema.index() method to createIndex for username field and i have also tried set the index: true and unique: true in username property, both are not working. Why is that ?
Here is what i have tried on mongoose schema index method:
AdminSchema.index({ username: 1 }, { unique: true });
console.log(AdminSchema.indexes());