我尝试向数据库中添加一个新用户,一次添加,第二次给出错误
{MongoError:E11000重复键错误索引:myproject.users。$ username_1 dup键:{:null} 在Function.create(D:\ projects \ myproject \ server \ node_modules \ mongodb-core \ lib \ error.js:43:12) 在toError(D:\ projects \ myproject \ server \ node_modules \ mongodb \ lib \ utils.js:149:22) 在coll.s.topology.insert(D:\ projects \ myproject \ server \ node_modules \ mongodb \ lib \ operations \ collection_ops.js:859:39) 在D:\ projects \ myproject \ server \ node_modules \ mongodb-core \ lib \ connection \ pool.js:532:18 在process._tickCallback(内部/进程/next_tick.js:61:11) 司机:对, 名称:“ MongoError”, 索引:0, 代码:11000, errmsg: 'E11000重复键错误索引:myproject.users。$ username_1 dup键:{:null}', [Symbol(mongoErrorContextSymbol)]:{}}
users.js
const express = require('express');
const router = express.Router();
const bcrypt = require('bcryptjs');
const validateRegisterInput = require('../../validation/register');
const User = require('../../models/User');
// @route GET api/users/test
// @desc Tests users route
// @access Public
router.get('/test', (req, res) => res.json({msg: 'Users Works'}));
// @route POST api/users/register
// @desc Register user
// @access Public
router.post('/register', (req, res) => {
const {errors, isValid} = validateRegisterInput(req.body);
// Check Validation
if (!isValid) {
return res.status(400).json(errors);
}
User.findOne({email: req.body.email}).then(user => {
if (user) {
errors.email = 'Email already exists';
return res.status(400).json(errors);
} else {
const newUser = new User({
name: req.body.name,
email: req.body.email,
password: req.body.password
});
bcrypt.genSalt(10, (err, salt) => {
bcrypt.hash(newUser.password, salt, (err, hash) => {
console.log(333)
if (err) throw err;
newUser.password = hash;
newUser
.save()
.then(user => res.json(user))
.catch(err => console.log(err));
});
});
}
});
});
module.exports = router;
Users.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const UserSchema = new Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true
},
password: {
type: String,
required: true
},
date: {
type: Date,
default: Date.now()
}
});
module.exports = User = mongoose.model('users', UserSchema);