Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

256
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda