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;
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:
if(savedUser.length)
(checking there are items in array)..findOne
instead of .find
which will return first document matching you query and null
otherwise.I would suggest using .findOne