Home > OS >  Used unique inside email index Mongodb, cannot alert 'user already registered'
Used unique inside email index Mongodb, cannot alert 'user already registered'

Time:04-15

unique:true does stop from adding to database, but only getting the catch(e) error message. Tried using the findOne method, but as a beginner, architecture keeps messing me up.

require('dotenv').config()
const express = require('express')
const cors = require('cors')
const bodyParser = require('body-parser')
const mongoose = require('mongoose')

const app = express();

const urlencodedParser = bodyParser.urlencoded({ extended: false })
app.use(bodyParser.json(), urlencodedParser);
app.use(cors());

const dbURI = 
`mongodb srv://${process.env.REACT_APP_DB_USERNAME}:${process.env.REACT_APP_DB_PASSWORD}@cluster0.sd1id.mongodb.net/register?retryWrites=true&w=majority`

mongoose.connect(dbURI, { useNewUrlParser:true, useUnifiedTopology:true })
.then((res) => {

    const User = mongoose.model('users', UsersSchema);
User.createIndexes();

Having issues here I think. Goes straight to error, and not the else loop.

app.post('/register', async (req, res) => {
    try {
        const user = new User(req.body);
        let result = await user.save();
        result = result.toObject();
        // console.log(result);
        if (result) {
            delete result.password;
            res.send(req.body);
            // console.log(result);
        } else {
            console.log("User already registered!");
        }
    } catch (e) {
        console.log("Something went wrong!");
    }
})

})
.catch(err => console.log(err))

const UsersSchema = new mongoose.Schema({
    email: {
        type: String,
        unique: true,
        required: true,
    },
    password: {
        type: String,
        required: true,
    }
})



app.listen(3001, () => console.log("Server is listening to port 3001"))

CodePudding user response:

There is a bit of confusion in your code...

app.js

require('dotenv').config()
const express = require('express')
const cors = require('cors')
const bodyParser = require('body-parser')
const mongoose = require('mongoose')

const app = express();

const createUser = require('registerController');

// repleace 3000 with a port number of your choice
const port = 3000 || process.env.PORT;

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(cors());

app.post('/register', createUser);

const dbURI = 
`mongodb srv://${process.env.REACT_APP_DB_USERNAME}:${process.env.REACT_APP_DB_PASSWORD}@cluster0.sd1id.mongodb.net/register?retryWrites=true&w=majority`

mongoose.connect(dbURI, { useNewUrlParser:true, useUnifiedTopology:true })
.then(() => {
app.listen(port, () => console.log(`Server listening on Port ${port}`));
});

User.js

const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
    email: {
        type: String,
        unique: true,
        required: true,
    },
    password: {
        type: String,
        required: true,
    }
});

module.exports = mongoose.model('User', userSchema);

registerController.js

const User = require('User');

const createUser = async (req, res) => {
    try {
        const user = await User.create(req.body);
        // console.log(user);
        if (user) {
            delete user.password;
            res.send(req.body);
            // console.log(user);
        } else {
            console.log("User already registered!");
        }
    } catch (e) {
        console.log("Something went wrong!");
    }
};

module.exports = createUser;
  • Related