Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

252
Vistas
Check if username or email exist in mongodb atlas

Im new to MERN. I want to print USER ALREADY EXIST if email or name already present. I used .find method but its not working. here,s the code

    const { response } = require('express')
    const express = require('express')
    const router = express.Router()
    const mongoose = require('mongoose')
    const User = mongoose.model("User") 'defined in user.js'
    const bcrypt = require('bcryptjs')
    
    
    router.post('/signup',(req,res)=>{
        const {name,email,password} = req.body
        if(!email || !password || !name){
           return res.status(422).json({"error":"please add all the fields"}) //status 422 means server has understood the request but cant proess 
        }
    
       User.find({email : email, name : name}).then((savedUser)=>{
           if(savedUser){
               return res.status(422).json({error:"user already exist."})
           }
    
           bcrypt.hash(password,6).then(hashedpassword=>{
            const user = new User({
                email,    //is also written as "email" : email
                password:hashedpassword,
                name
            })
     
            user.save().then(user=>{
                res.json({message:"saved sucessfully"})
            }).catch(err=>{
                console.log(err)
            })  
           }) /
        
       }).catch(err=>{
           console.log(err)
       })
    
    }) 
    
    
    module.exports = router; 
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Using .find() in mongoose returns array of documents, even if there is one record it will be inside an array. The problem is when no document matches your query .find() will return an empty array. making savedUser = [] and when you check it in here if(savedUser) it always returns true, resulting in below block to always run

return res.status(422).json({error:"user already exist."})

You can overcome this problem either by using:

  1. if(savedUser.length) (checking there are items in array).
  2. or by using .findOne instead of .find which will return first document matching you query and null otherwise.

I would suggest using .findOne

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda