I have created a new Mongo collection to a new project, but when I try to create a new user, I get the following error:
MongoError: E11000 duplicate key error collection: GestorMedico.users index: username_1 dup key: { username: null }
My User schema is the following:
const { Schema, model } = require("mongoose");
const userSchema = new Schema({
nombreEmpresa: {
type: String,
unique: true,
required: true
},
email: {
type: String,
required: true
},
telefono: {
type: String,
required: true
},
contraseña: {
type: String,
required: true
}
}, {
timestamps: true,
versionKey: false
});
module.exports = model("Users", userSchema);
My function is the following:
userCtrl.createUser = async (req, res) => {
const newUser = new User(req.body);
newUser.contraseña = await crypt.encryptPassword(newUser.contraseña);
await newUser.save();
res.status(200).json({
status: "OK",
message: "User created"
});
};
And my collection looks like:
I have reused the backend of one of my old projects, which have a "username" in a schema.
username
as a part of your schema and you have created an index on it. Please make a change on schema or drop index on the username. – South