L
L
low molecular macro2021-04-10 02:53:08
JavaScript
low molecular macro, 2021-04-10 02:53:08

How to make checking for duplicate values ​​in Mongo more elegant?

Before creating a new user and adding it to the database, I want to make sure that the phone number has not yet been used for registration, and the nickname is not yet taken by anyone.
The schema for these fields says unique: true. But the inconvenience is that when the validation fails, the response is a hard-to-read error that is not easy to parse to display a message about exactly which field is duplicated (by the way, why is this? Errors with required, for example, have a much more convenient form).
Another inconvenience of built-in validation for duplicates is that if there are several duplicate fields, then only the first field will be returned as an error (again, in the case of required, an array of all empty fields is returned). And this is not good for me, because I want to immediately show the user what fields he needs to change. And not step by step, until there are no errors at all.
What I'm getting at... I wrote my own validator, but it seems crooked to me. I want to know your opinion, how can I improve it? Or do it completely differently?

exports.createUser = async (req, res) => {
  try {
    // информация о пользователе, которая пришла из формы
    const incomingData = req.body;

    // массив под поля-дубликаты
    const duplicateErrors = [];

    const nickDuplicate = await User.findOne({
      nickname: incomingData.nickname
    });
    // добавление никнейма в массив дублирующихся полей
    if (nickDuplicate) {
      duplicateErrors.push("nick");
    }

    const numDuplicate = await User.findOne({
      number: incomingData.number
    });
    if (numDuplicate) {
      duplicateErrors.push("num");
    }

    // если хоть одно из полей дублируется - будет отправлена ошибка 400
    if (duplicateErrors.length) {
      return res.status(400).json(duplicateErrors);
    }

    await User.create({
      nickname: incomingData.nickname,
      number: incomingData.number,
      bio: incomingData.bio
    });

    res.status(201).json("success");
  } catch (err) {
    res.status(500).json("Что-то пошло не по плану...");
  }
};

I especially dislike this type of construction:
const nickDuplicate = await User.findOne({
      nickname: incomingData.nickname
    });
    // добавление никнейма в массив дублирующихся полей
    if (nickDuplicate) {
      duplicateErrors.push("nick");
    }

Back to the page, I pass an array of fields whose values ​​are already found in the database. Already on the page, based on the content of the resulting array, I display messages under the corresponding inputs

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question