Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

253
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!