2

I'm new to nodejs. I've a MEAN stack project employee, department and user roles models. While creating the employee i'm checking for department and userrole

const mongoose = require('mongoose');
const Employee = require('../models/employee');
const UserRoles = require('../models/userRole');
const Department = require('../models/department');
const _ = require('lodash');

exports.create_employee = (req, res, next) => {

    Department.findById(req.body.deptID)
        .then( dept => {
            if( !dept ) {
                return res.status(404).json({
                    message: 'Department not found'
                });
            }
            return UserRoles.findById(req.body.userRoleID)
                .then( role => {
                    if( !role ) {
                        return res.status(404).json({
                            message: 'User role not found'
                        });
                    }
                    const employee = new Employee({
                        _id: new mongoose.Types.ObjectId(),
                        name: req.body.name,
                        designation: req.body.designation,
                        doj: req.body.doj,
                        dob: req.body.dob,
                        bloodGroup: req.body.bloodGroup,
                        deptID: req.body.deptID,
                        userRoleID: req.body.userRoleID,
                        empCode: req.body.empCode
                    });
                    return employee.save();
                })
        })
        .then(result => {
            let ob = _.omit(result, ['__v']);
            res.status(201).json({
                createdEmployee: ob
            });
        })
        .catch(err => {
            res.status(500).json({
                message: 'Internal Server Error'
            });
        });
};

When i try to create an employee with deptID and userRoleID which are not present in response am getting correct response as not found. But in terminal am getting below error

enter image description here

I think am doing some wrong return please correct me!!

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
VIK6Galado
  • 650
  • 14
  • 32

2 Answers2

3

Can't set headers after they are sent

You are replying to the request more than once. Find out which code paths get executed that cause this and fix them.

You should only res.status()... once for every request.

nicholaswmin
  • 21,686
  • 15
  • 91
  • 167
3

Response is already sent and again a response is being sent by MongoDB callback (UserRole). Your Department.findById and UserRoles.findById queries are independent to each other so here Promise chaining not required.

Very well written answer on Response header can be found here...

Error: Can't set headers after they are sent to the client

You can try this modified code.

exports.create_employee = async (req, res, next) => {
 try {
    let dept = await Department.findById(req.body.deptID);
    if (!dept) {
        return res.status(404).json({
            message: 'Department not found'
        });
    }
    let role = await UserRoles.findById(req.body.userRoleID);
    if (!role) {
        return res.status(404).json({
            message: 'User role not found'
        });
    }
    // onward code will execute only when role and dept exists.
    const employee = new Employee({
        _id: new mongoose.Types.ObjectId(),
        name: req.body.name,
        designation: req.body.designation,
        doj: req.body.doj,
        dob: req.body.dob,
        bloodGroup: req.body.bloodGroup,
        deptID: req.body.deptID,
        userRoleID: req.body.userRoleID,
        empCode: req.body.empCode
    });
    const result = await employee.save();

    let ob = _.omit(result, ['__v']);
    res.status(201).json({
        createdEmployee: ob
    });

} catch (err) {
    res.status(500).json({
        message: 'Internal Server Error'
    });
}};
Abhishek Singh
  • 1,631
  • 1
  • 17
  • 31