How to solve MongoServerError: E11000 duplicate key error?

Issue

Index.Js File:

const cookieSession = require("cookie-session");
const express = require("express");
const app = express();
const helmet = require("helmet");
const morgan = require("morgan");
const dotenv = require("dotenv");
const mongoose = require("mongoose");
const userRoute = require("./routes/user")
const authRoute = require("./routes/auth")

dotenv.config();


//Mongoose Connect

mongoose.connect(process.env.MONGO_URL, {useNewUrlParser: true}, (err) =>
{
    console.log("mongdb is connected");
});

//middleware

app.use(express.json());
app.use(helmet());
app.use(morgan("common"));

app.get("/", (req, res) => {
    res.send("Welcome to home page");
})

app.use("/api/auth", authRoute);
app.use("/api/user", userRoute);

app.listen(5000,function(err)
{ 
    if(err)
        console.log("Server not connected")
    console.log("Connnection is established");
})

Auth.Js File

const router = require("express").Router();
const User = require('../model/Users');


//REGISTER

router.get("/register", async (res,req)=> {
    const user = await new User({
        username: "gauravnegi",
        password: "123456",
        email: "[email protected]",
    });

    await user.save();
    res.send("ok");

});


module.exports = router;

Error:

return callback(new error_1.mongoservererror(res.writeerrors [0] ))

Full Error Snippet:

Click to view full error

How to resolve above error?

Solution

Dear it is not a server side error it’s a client side error b/c you have defined somewhere some field {unique:true} in your model! So you should wrap your function inside try-catch block for example

router.get("/register", async (res,req)=> {
 try{
    const user = await new User({
        username: "gauravnegi",
        password: "123456",
        email: "[email protected]",
    });

    await user.save();
    res.send("ok");
 }catch(error){
  //check if it was a duplication error
 if(error.code==11000) // show user that it is unique path
 and handle other validation error
}
    

});

Answered By – Adnan Malik

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published