Friday, 12 July 2019

UnhandledPromiseRejectionWarning: MongoError: E11000 duplicate key error collection: test.users index: user_1 dup key: { : null Which line in my code is throwing this error?

Hi, My model.js looks like ``` const mongoose = require('mongoose'); const Schema = mongoose.Schema;const userSchema = new Schema({ username: { type: String, required: true, unique: true }, hash: { type: String, required: true }, createdDate: { type: String, required: true, default: Date.now() }, discordID: { type: String, default: null } })userSchema.set('toJson', { virutals: "None" })module.exports= mongoose.model("User",userSchema); ```server.js ``` const config = require('../config.json')const jwt = require('jsonwebtoken'); const bcrypt = require('bcryptjs'); const db = require('../_helpers/db'); const User = db.User;module.exports ={ register, login }function register({ username, password, discordId }) { // handle if username/password in route if (!discordId) { discordId = null; };const person = User.findOne({ username: username }); if (!person) { throw "User Already Exists" } const salt = bcrypt.genSaltSync(10); const hash = bcrypt.hashSync(password, salt); let user = {}; try { user = new User({ username: username, hash: hash, discordId: discordId }); } catch (MongoError) { throw MongoError } try { user.save(); } catch (MongoError) { throw "UserIsAlreadyMade" } let token = jwt.sign(user.toJSON(), config.jwt.secret, { expiresIn: '1h' }); return token; } ```controlller.js ``` const express = require('express'); const userService = require('./service'); const bodyParser = require('body-parser');const router = express.Router();router.use(bodyParser.urlencoded({ extended: false })); router.use(bodyParser.json());router.get('/church', (req, res) => { res.status(200).json({ success: true }) });router.route('/register') .post((req, res) => { console.log(req.body); if (!req.body.username || !req.body.password){ res.status(400).json({ success: false, error: "No username or password" }); throw "Incorrect parameters" }; let token; try { token = userService.register(req.body); } catch (err) { res.status(400).json({ success: false, message:err }); throw err }; res.cookie('Information', token, { maxAge: 900000, httpOnly: true }); res.status(200).json({ success: true, token: token }); });router.post('/login', (req, res) => {})module.exports = router; ```The error is being thrown somewhere, but the log doesn't specify which line? Also, it says a key inst unique, but doesn't tell me which key? I am sure it is the username, because that is the only key I set to unique, however, that username doesn't exist in my database.Another question: Even if the error occurs, my try/catch block around token doesn't send a 400, rather, it continues and sens a 200 status code?

Submitted July 12, 2019 at 09:08PM by HellD

No comments:

Post a Comment