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);
11000specifies "duplicate key error".