2

In a MEAN app, am trying to add a document in mongoDB collection using mongoose save() method. It gives the below error. Tried on Google - but all refer to duplicate key error.

core.js:4197 ERROR 
HttpErrorResponse {headers: HttpHeaders, status: 500, statusText: "Internal Server Error", url: "http://localhost:3000/api/user/add", ok: false, …}
error:
error:
code: 11000
driver: true
index: 0
keyPattern:
email: 1
__proto__: Object
keyValue:
email: null
__proto__: Object
name: "MongoError"
__proto__: Object
__proto__: Object
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
message: "Http failure response for http://localhost:3000/api/user/add: 500 Internal Server Error"
name: "HttpErrorResponse"
ok: false
status: 500
statusText: "Internal Server Error"
url: "http://localhost:3000/api/user/add"
__proto__: HttpResponseBase

My code in nojejs route file where this error is caused is as follows.

const express = require('express');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const User = require('../models/user');
const router = express.Router();
router.post('/add', (req, res, next) => {
    bcrypt.hash(req.body.password, 10)
        .then(hash => {
            const user = new User({
                username: req.body.username,
                password: hash
            });
            console.log(user); // THIS GIVES CORRECT RESULT in the console. Shows the new user object
            user.save() // THIS CAUSES ERROR
                .then(result => {
                    res.status(201)
                        .json({
                            message: 'User added.',
                            result: result
                        });
                })
                .catch(err => {
                    res.status(500)
                        .json({
                            error: err
                        });
                });
        });
});

The user model is very simple as follows. It had an email field earlier, which was deleted. And previous test users from mongoDb collection were also deleted. Now there is an existing user based on revised model in the users collection.

const mongoose = require('mongoose');
const uniqueValidator = require('mongoose-unique-validator');

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

userSchema.plugin(uniqueValidator);

module.exports = mongoose.model('User', userSchema);
5
  • In case you are seeing the log in console twice check this npmjs.com/package/mongoose-unique-validator#caveats The validator could case the problem. Commented Sep 16, 2020 at 9:08
  • The MongoDB server error code 11000 specifies "duplicate key error". Commented Sep 16, 2020 at 9:09
  • If i understand the error correctly then it says that you have duplicate emails in the db. Haven't you(or someone else in your team) previously set the unique index on email property in the db?? Commented Sep 16, 2020 at 9:17
  • @Molda - yes there was an email field earlier in the db which was set as Unique. But later the field was deleted and the users from the db were also deleted. How do I check if the db still has the email field in there. Also now the front end form does not have email field for adding a user and also the User Model does not have email field either. So wondering why it gives an error on email field? Commented Sep 18, 2020 at 10:49
  • @hemant you seem to have a unique index on email field so just drop it using this docs.mongodb.com/manual/reference/method/… The reason you get the error even if you don't insert email field is that you are essentialy inserting null for the email and since the field is unique you can't have more then one null value for the email. Commented Sep 19, 2020 at 6:51

1 Answer 1

0

In your userSchema, you set username to be unique. Hence you should not try to create a new user with already used username. Check if you are trying to make the 'add' post request with already created username

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.