0

Hello I have a schema and when I am passing values , it is showing that values are empty and required. I am not getting why.

Model.js:-

var adminSchema = new mongoose.Schema({
    companyName : {
                type: String,
                required: "Company  name can't be empty.",
                required: false
                },  
    companyID:  {
                type: String,
                },              
    address :   {
                type: String,
                required: "Address can't be empty.",
                },
    contactDetails : {
                type: String,
                required: "Company contact number can't be empty.",
                },
    admins: {
                        email :     {
                                    type: String,
                                    required: "Email can't be empty.",
                                    unique: true
                                    },
                        password:   {
                                    type: String,
                                    required: "Password name can't be empty."
                                    },
                        firstName : {
                                    type: String,
                                    required: "First name can't be empty."
                                    },
                        lastName : {
                                    type: String,
                                    required: "Last name can't be empty."
                                    },  
                        phoneNumber :   {
                                    type: String,
                                    required: "Reqired for further contact. Can't be empty."
                                    },
                        designation :   {
                                    type: String,
                                    required: "Designation can't be empty."
                                    },          
                        verified: { 
                                    type: Boolean, 
                                    default: false 
                                    },
                        role: String,
                        emailResetTokenn: String,
                        emailExpires: Date,
                        saltSecret: String,//this is user for encryption and decryption of password 
                        users:[]    
            }                       
});



// Adding custom validation for email.
adminSchema.path('admins.email').validate((val) => {
    emailRegexx = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/ ;
    return emailRegexx.test(val);   
}, 'Invalid email');


//Pre event to trigger saltSecret before save function in user controller
adminSchema.pre('save', function (next){
    bcryptt.genSalt(10, (err, salt) => {            
        bcryptt.hash(this.admin.admins.password, salt, (err, hash) => { 
            this.admin.admins.password = hash ;
            this.admin.admins.saltSecret = salt;
            next();
        });
    });
});

mongoose.model('Admin', adminSchema); 

Controller file:-

const mongoose = require ('mongoose');
const Admin = mongoose.model('Admin');
var MongoClient = require('mongodb').MongoClient;

module.exports.registerAdmin = (req, res, next) =>{ 

    var admin = new Admin();
    admin.companyName = req.body.companyName;
    admin.address = req.body.address;
    admin.contactDetails  = req.body.contactDetails;
    admin.admins = {
                  email : req.body.email,
                  password: req.body.password,
                  firstName : req.body.firstName, 
                  lastName : req.body.lastName,
                  phoneNumber : req.body.phoneNumber,
                  designation : req.body.designation,
                  role : "admin",
                  id : req.body._id 
    }; 

const secret = crypto.randomBytes(20);
const hash = crypto.createHmac('sha256', secret)
                   .update(secret + admin.admins.email)
                   .digest('hex');

const reqq = crypto.createHash('md5').update(admin.companyName).digest('hex');

let valueNum = reqq.match(/\d/g).join("").toString().substring(0,6);

admin.companyID = valueNum;

var expires = new Date();
expires.setHours(expires.getHours() + 6);

    admin.admins.emailResetTokenn = hash;
    admin.admins.emailExpires = expires;    
    admin.save((err, doc) =>{});

I know I am doing some silly mistake , but not getting exactly what am I missing.

When testing I am passing :-

{
    "companyName":"Microsoft",
    "address": "AUS",
    "contactDetails" : "54534454",
    "admins" : {
        "email" : "kapa@clickmail.info",
        "password" : "something#1",
        "firstName" : "hdsdsds",
        "lastName": "Ghodsdsdsh",
        "phoneNumber" : "4544343",
        "designation" : "Software Engineer"
    }
}

And the output is :-

[
    "Email can't be empty.",
    "Password name can't be empty.",
    "First name can't be empty.",
    "Last name can't be empty.",
    "Reqired for further contact. Can't be empty.",
    "Designation can't be empty."
]

Had I defined the schema structure in a wrong way ?

A little suggestion will be appreciated. Thanks.

EDIT:- Expected return

{
    "companyName":"Microsoft",
    "companyId" : "4554"
    "address": "AUS",
    "contactDetails" : "54534454",
    "admins": {
        "email" : "bayicucasu@first-mail.info",
        "password" : "dffooto465m56.545mom3$5$6.4$%$%$64brgg",
        "firstName" : "hdsdsds",
        "lastName": "Ghodsdsdsh",
        "phoneNumber" : "4544343",
        "designation" : "Software Engineer",
        "id" : "565645vfbtrbfcv678",
        "verified": false,
        "role" : "admin",
        "emailResetTokenn" : "45455454rbgtbg$$t4@67&jyynjyj",
        "emailExpires": "21-05-2016 17:00:00",
        "saltSecret": "dfjduh%ufheHUHF7.dfu%#jj",
        "users":[]        
}
}
NoobCoder
  • 493
  • 8
  • 25

1 Answers1

1

In your code, for example, email field, you get it by using:

email : req.body.email

It means that the email must be in the top level of the request body

Try something like this:

{
    "companyName":"Microsoft",
    "address": "AUS",
    "contactDetails" : "54534454",
    "email" : "kapa@clickmail.info",
    "password" : "something#1",
    "firstName" : "hdsdsds",
    "lastName": "Ghodsdsdsh",
    "phoneNumber" : "4544343",
    "designation" : "Software Engineer"
}

If you want to keep the request body, I think you have to change code like this:

admin.admins = {
                  email : req.body.admins.email,
                  password: req.body.admins.password,
                  firstName : req.body.admins.firstName, 
                  lastName : req.body.admins.lastName,
                  phoneNumber : req.body.admins.phoneNumber,
                  designation : req.body.admins.designation,
                  role : "admin",
                  id : req.body.admins._id 
    }; 

Something like that, also notice that there is no _id field in the request body

If you don't want to specify an _id in request body, you can generate it by using

id: mongoose.Types.ObjectId()

or any random method that you like

0xh8h
  • 3,271
  • 4
  • 34
  • 55
  • No , I want my schema structure to be same as I have mentioned. Any changes to be done in this part ? – NoobCoder May 21 '19 at 07:01
  • Also I used this `id: mongoose.Types.ObjectId()` for generating `_id` inside `admins:{}`, but it didn't worked – NoobCoder May 21 '19 at 08:32
  • @NoobCoder hmm, I'm not sure why. You can ask for more info here https://stackoverflow.com/questions/17899750/how-can-i-generate-an-objectid-with-mongoose or https://github.com/Automattic/mongoose/issues/5082 – 0xh8h May 22 '19 at 02:15