C
C
Cyril2020-03-27 23:20:34
MongoDB
Cyril, 2020-03-27 23:20:34

How to create a unique field in Mongoose?

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);


The documentation says that the unique attribute does not validate for uniqueness when a new entry is added.

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

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

There will be no exceptions.

How then to check the uniqueness of the login field ? It turns out you have to define a hook
// Срабатывает до операции сохранения
userSchema.pre("save", function() { 
});

and in it to check if such a login exists? Or are there some other ways?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey Makushkin, 2020-03-28
@andreimakushkin

When trying to create a user with an already existing login, Mongo will throw an error, something like this:
E11000 duplicate key error collection...
It is better to additionally handle this scenario manually

const createUser = async (req, res) => {
  // Проверяем наличие входящих данных
  if (!req.body.login || !req.body.passwd) {
    return res.status(400).json({
      message: 'Логин и пароль обязательны для заполнения',
    });
  }

  try {
    // Проверяем, есть ли в бд пользователь с таким логином
    const user = await User.findOne({ login: req.body.login }).exec();

    // Если пользователь найден возвращаем ошибку, иначе создаем его
    if (user) {
      res.status(409).json({ message: 'Пользователь с таким логином уже зарегистрирован' });
    } else {
      await User.create(req.body);
      res.status(201).json({ message: 'Пользователь создан' });
    }
  } catch (error) {
    console.error(error);
    res.status(400).end();
  }
};

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question