Search code examples
node.jsmongodbexpressmongoose-schema

Comparison of models by parameters from the database and form


I encountered such a problem. on the client, the user fills out the registration form, I accept it on the backend (in json format). Next, I need to make a comparison. If a document by email parameter already exists in the database, then send an error; if there is no such document with such an email, then create a new document in the database.

There will be a piece of my route responsible for these actions

    router.post('/register', checkNotAuthenticated, async (req, res) => {
      try {
           //Block for passport session
        const hashedPassword = await bcrypt.hash(req.body.password, 10)
        const username = users.push({
          id: Date.now().toString(),
          name: req.body.name,
          email: req.body.email,
          password: hashedPassword
        })
        //End of block for passport session

        const candidate = await User.findOne(username.email)
        if(candidate)  {
          console.log('User have been already registered!')
          console.log(candidate)
        } else {
          const participant = new User({
            name: req.body.name,
            email: req.body.email,
            password: hashedPassword
        })
        await participant.save()
        }
         res.redirect('/login')
      } catch(e) {
        res.redirect('/register')
        console.log(e);
      }

If my user collection is empty, then a new document is created( for example:

{ inst: null,
  vk: null,
  _id: 5e10b72626f9107d861621c0,
  name: 'Ivan',
  email: 'w@w',
  password:
   '$2b$10$/2dDrTMCOXSZnaIgOgFEBuNKuU8mbRFKyV9.4U6brERsLpOVJoBAS',
  __v: 0 }

), but if at least one document exists, then it does not allow me to create a user(User have been already registered!). Apparently he checks in general for the existence of a document with email parameters, but I don’t know how to find the exact document with the email parameter that entered the user on the form on the client( const candidate = await User.findOne(username.email/* how to refer correctly to this parameter which the user drives into the form?.*/))


Solution

  •  User.findOne({'email':username.email})