In Mongoose to create a unique field?

I have a user schema like this:
const userSchema = new Schema(
{
 login: {
 type: String,
 required: true,
 unique: true
},
 passwd: {
 type: String,
 required: true
}
{
 timestamps: {
 createdAt: "created_at",
 updatedAt: "updated_at"
}
}
);

const User = model("user", userSchema, 'user', true);


In the documentation says that the attribute is unique not validated for uniqueness when adding new records.

That is, I can add two users with the same login:
User.create({
 login: "user123",
 passwd: "123"
});

User.create({
 login: "user123",
 passwd: "123"
});

No exceptions will be made.

How to check the uniqueness of fields to login? I have to define a hook
// Triggered before saving
userSchema.pre("save", function() { 
});

and it can test whether a login? Or are there any other ways?
April 9th 20 at 10:36
1 answer
April 9th 20 at 10:38
When you try to create user with existing username, Mongo will throw an error something like this:
E11000 duplicate key error collection...

It is better to manually handle this scenario

const createUser = async (req, res) => {
 // Check for incoming data
 if (!req.body.login || !req.body.passwd) {
 return res.status(400).json({
 message: 'the Username and password is mandatory',
});
}

 try {
 // Check whether the database user with this login
 const user = await User.findOne({ login: req.body.login }).exec();

 // If the user is found return an error, otherwise create it
 if (user) {
 Res. status(409).json({ message: 'User with this login is already registered' });
 } else {
 await User.create(req.body);
 Res. status(201).json({ message: 'User created' });
}
 } catch (error) {
console.error(error);
Res. status(400).end();
}
};

Find more questions by tags MongoDBMongoose