MongoError:E11000重复键错误集合:ProductsRepo.users索引:username_1 dup键:{username:null}

时间:2020-10-29 20:01:35

标签: javascript node.js reactjs mongodb express

我有一个注册页面,客户端可以在其中创建一个帐户并将其保存到数据库中,但是在创建帐户时出现以下错误:(node:23404)UnhandledPromiseRejectionWarning:MongoError:E11000重复密钥错误集合:ProductsRepo.users索引:username_1 dup键:{username:null}

代码模型:

const mongoose = require('mongoose')

//how a user will be stored in the mongodb schema
const userSchema = new mongoose.Schema({
    name: { type: String, required: true },
    email: { type: String, required: true, unique: true, dropDups: true },
    password: { type: String, required: true, minlength: 3, trim: true },
    isAdmin: { type: Boolean, required: true, default: false },
})

const userModel = mongoose.model('Users', userSchema)

module.exports = userModel

代码路由器:

const express = require('express')
const User = require('../models/userModel')
const getToken = require('../util')

const router = express.Router()

//create route for sign in
router.post('/signin', async (req, res) => {
    //send query to DB
    const signinUser = await User.findOne({
        email: req.body.email,
        password: req.body.password,
    })
    if (signinUser) {
        res.send({
            _id: signinUser.id,
            name: signinUser.name,
            email: signinUser.email,
            isAdmin: signinUser.isAdmin,
            token: getToken(signinUser),
        })
    } else {
        res.status(401).send({ msg: 'Invalid email or Password' })
    }
})

//create route for register
router.post('/register', async (req, res) => {
    //send query to DB
    const user = new User({
        name: req.body.name,
        email: req.body.email,
        password: req.body.password,
    })
    const newUser = await user.save()

    if (newUser) {
        res.send({
            _id: newUser.id,
            name: newUser.name,
            email: newUser.email,
            isAdmin: newUser.isAdmin,
            token: getToken(newUser),
        })
    } else {
        res.status(401).send({ msg: ' email already taken!' })
    }
})



module.exports = router

代码RegisterAction:

const register = (name, email, password) => async (dispatch) => {
    dispatch({
        type: actions.USER_REGISTER_REQUEST,
        payload: {
            name,
            email,
            password,
        },
    })
    try {
        const { data } = await Axios.post(
            'http://localhost:5000/users/register',
            {
                name,
                email,
                password,
            }
        )
        dispatch({ type: actions.USER_REGISTER_SUCCESS, payload: data })
        Cookie.set('userInfo', JSON.stringify(data))
    } catch (error) {
        dispatch({ type: actions.USER_REGISTER_FAIL, payload: error.message })
    }
}

代码注册页面:

function Signup(props) {
    const [name, setName] = useState('')
    const [email, setEmail] = useState('')
    const [password, setPassword] = useState('')
    const [rePassword, setRePassword] = useState('')

    const userRegister = useSelector((state) => state.userRegister)
    const { loading, userInfo, error } = userRegister

    const dipsatch = useDispatch()
    useEffect(() => {
        if (userInfo) {
            props.history.push('/login')
        }
    }, [userInfo])

    //handlesubmit
    const submitHandler = (e) => {
        e.preventDefault()
        dipsatch(register(name, email, password, rePassword))
    }
    return (
        <body className="sign-body">
            <div>
                <Nav />
                <h2 className="signup-h">Signup for free</h2>
                <div className="signup">
                    <form onSubmit={submitHandler}>
                        <label>Enter username</label>
                        <br />
                        <input
                            type="text"
                            for="name"
                            onChange={(e) => setName(e.target.value)}
                        ></input>
                        <br />
                        <label>Enter email</label>
                        <br />
                        <input
                            type="email"
                            for="email"
                            onChange={(e) => setEmail(e.target.value)}
                        ></input>
                        <br />
                        <label>Enter password</label>
                        <br />
                        <input
                            type="password"
                            for="password"
                            onChange={(e) => setPassword(e.target.value)}
                        ></input>
                        <br />
                        <label htmlFor="rePassword">Confirm password</label>
                        <br />
                        <input
                            type="Password"
                            onChange={(e) => setRePassword(e.target.value)}
                        ></input>
                        <br />

                        <button type="submit">Signup</button>

                        <p className="have-cc">
                            {' '}
                            already have an account? <a href="/login">login</a>
                        </p>
                    </form>
                </div>
            </div>
        </body>
    )
}

0 个答案:

没有答案