Home > Software design >  How to solve MongoServerError: E11000 duplicate key error?
How to solve MongoServerError: E11000 duplicate key error?

Time:09-11

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?

CodePudding user response:

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
}
    

});
  • Related