Home > database >  I want to verify if a user is existing in database using MERN stack
I want to verify if a user is existing in database using MERN stack

Time:03-14

Hello everybody im kindo new to web developpemnt and im workign on a project and exaclty on authentification and i want to verify if a user is already exisiting in database because if i register multiple times with the same email it got saved in the database again... so im using mern stack and heres my code:

Server index.js :

app.use(cors())
app.use(express.json())

mongoose.connect('mongodb srv://...')

app.post('/api/register', async (req, res) => {
    console.log(req.body)
    try {
        const user = await User.create({
            name: req.body.name,
            email: req.body.email,
            password: req.body.password,
        })
        res.json( { status: 'ok' })
    }catch (err) {
        res.json({ status: 'error', error: 'Duplicate email' })
    }
})

CodePudding user response:

Make changes in mongo User Schema with unique as true

 email : {
        type:String,
        required: true,
        unique: true
    }

CodePudding user response:

i already have this on usermodel :

const mongoose = require("mongoose");

const User = new mongoose.Schema(
    {
        name: { type: String, required: true },
        email: { type: String, unique: true, required: true },
        password: { type: String, required: true },
        quote: { type: String },
    },
    { collection: "user-data" }
);

const model = mongoose.model("UserData", User);

module.exports = model;
  • Related