Home > Back-end >  How to check email and mobile present or not in my mongodb database?
How to check email and mobile present or not in my mongodb database?

Time:12-28

const express = require('express');
const router = express.Router();

require('../db/conn');
const User = require('../model/userSchema');

router.get('/', (req, res) => {
    res.send(`Hello World from the server from router.`);
});


router.post('/register', async (req, res) => {
    
    const { name,email,phone,work,password,cpassword } = req.body;
    
    if(!name || !email || !phone || !work || !password || !cpassword){
        return res.status(422).json({error:"please fill all the fields data.."});
    }

    try {
        
        const userExist = await User.findOne({ "$or": [ { email: email }, { phone: phone} ] })

        if(userExist.email==email){
            return res.status(422).json({error:"Email ID is already exist."});
        }else if(userExist.phone==phone){
            return res.status(422).json({error:"Mobile no is already exist."});
        }

        const user = new User({name,email,phone,work,password,cpassword});

        const userRegister = await user.save();

        if(userRegister){
            res.status(201).json({message:"User Registered Successfully."});
        }else{
            res.status(500).json({error:"Failed to regsiter user."});
        }
    } catch (err) {
        console.log(err);
    }
});module.exports = router;

I write the code for checking email and mobile present or not in database. Actually i want to check differently not in a single statement like Email or mobile is already present. So i write this code but for checking it worked fine but when i put all unique data than one error is coming. data is not stored in database. Error is

TypeError: Cannot read properties of null (reading 'email') at E:\MERN Project\Server\router\auth.js:20:22 at processTicksAndRejections (node:internal/process/task_queues:96:5)

CodePudding user response:

I think the problem is how you create your new record, try instead of

const user = new User({name,email,phone,work,password,cpassword});

const userRegister = await user.save();

to use the schema to create the record.

const user = await User.create({name,email,phone,work,password,cpassword});
await user.save();

actually if you do not change the any property after creation you can skip the save.

CodePudding user response:

The easiest way to achieve this would be to use validator packages. So, the data won't get save if all conditions are not satisfied.

I recommend using 'joi'. Please go through the documentation for a deeper understanding.

https://www.npmjs.com/package/joi

  • Related