Search code examples
node.jsarraysdatabaseexpressmongoose-schema

Trying to save a database But when I test the api on Postman I am getting an error


I am trying to save some data into database using mongoose but when I tried to test it on postman I get an error:If anyone can help me So please help. I am stuck at this point since two days .

Getting this Error in Postman(Coming from usercontroller.js)

{
"status": false,
"err": {
    "driver": true,
    "name": "MongoError",
    "index": 0,
    "code": 11000,
    "keyPattern": {
        "Email": 1
    },
    "keyValue": {
        "Email": null
    }
}

}

MY USERCONTROLLER.JS FILE

       //INIT
       const express = require('express');
       const router = express.Router();
        const bodyparser = require('body-parser');
        const bcrypt = require('bcryptjs');
       const {check , validationResult, Result } = require('express-validator');

// MIDDLEWARE SET-UP
      router.use(bodyparser.json());
    router.use(bodyparser.urlencoded({extended: true}));


   // Importing User.js file

      const users = require('../models/user');



   //Laying Routes/Pipes


    // Pipe Number 1)
      router.all('/data',(req,res)=>{
    return res.json({
        status : 'ok'
       });
     });


//Pipe Number 2)
    router.post('/newdata',
    [
        check('username').not().isEmpty().trim().escape(),
        check('password').not().isEmpty().trim().escape(),
        check('body').not().isEmpty().trim().escape(),
        check('email').isEmail().normalizeEmail()
        
    ],
    (req, res)=>{
        
       // This code causes problem
        const errors = validationResult(req);
        if (!errors.isEmpty()) {
            return res.status(422).json({
                status : false,
                errors : errors.array()
            });
        };
        const hashedpass = bcrypt.hashSync(req.body.password, 10);

       
        users.create({
            username : req.body.username,
            password : hashedpass,
            body : req.body.body,
            email : req.body.email,
        },(err,Result)=>{
            if (err) {
                return res.json({
                    status:false,
                    err: err
                })
            };

            return res.json({
                status : true,
                result: Result
            })
        })
    });
        
     //MODEL EXPORT
     module.exports = router; 

My User.js File

   //INIT
     const mongoose = require("mongoose");

   //User Schema

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

  })
     // Creating MODEL

    mongoose.model('users', userSchema);

      // Exporting this Modules is Controller.js file

     module.exports = mongoose.model('users');

My index.js file

        //**********   INIT  **************

        const express = require('express');
        const app = express();
        const cors = require('cors');
        const mongoose = require('mongoose');
        const assert = require('assert');
        const bodyparser = require('body-parser');
        const morgan = require('morgan');
        const port = 3000;


        //**********   Importing Required Files  **************

        const User = require('../controllers/usercontrollerx');
        app.use('/user', User);
        app.use(bodyparser.urlencoded({
            extended: true
        }));
        app.use(express.json());
        //**********   Connacting to MongoDB  **************

        mongoose.connect('mongodb://127.0.0.1:27017/mongo_test',{
            useCreateIndex : true, useUnifiedTopology: true, useCreateIndex : true , useNewUrlParser : true
        }, (err,link)=>{ 
            // If error
                assert.equal(err, null, "Connection Failed");
            //If connected 
            console.log('----------------------------');
            console.log('Connetion Established')
            console.log('----------------------------');
        });

        //**********   Connacting to Server  **************

        app.listen(port, (req,res)=>{
            console.log('----------------------------');
            console.log('Connect to the Port :' + port)
        })




        //**********   Laying Pipes **************

        app.get('/',(req,res)=>{
            res.send("<a href='/user/newdata'>Go to users</a>");
            
        });



        //**********   Middle Ware SetUp **************

        app.use(morgan('dev'));
        app.use(cors());
        const { json } = require('body-parser');

Solution

  • The error code 11000 means that there's already a document with the given value - in your case there's a document with value null for the email field.

    Instead of a unique index you may want to create a partial index on the email field as those indices allow null values as explained here.