Vaibhav Singh Vaibhav Singh - 1 month ago 7
Javascript Question

Add element to existing JSON in javascript

Hi I have the following JSON named departments. When i do console.log(departments) i get this.

{ _id: 58089a9c86337d1894ae1834,
departmentName: 'Software Engineering',
clientId: '57ff553e94542e1c2fd41d26',
hodName: 'Mr Shekar Krishna',
noOfEmployees: 90,
hodId: 'djekjakejkjkjekajk3j33',
__v: 0 }


But when i try to assign a value like hodId to a variable like this.

var hodId=departments.hodId;

and then do console.log i get undefined.

Also i need to add this value "hodId" to t to another JSON "user" which is currently like this:

{ fullName: 'Rohit',
password: '123',
contactNum: '00000',
homeNum: '9998889999',
officeNum: '9998889999',
emailId: 'dv000d0v@yopmail.com',
employeeAddress: '10 ,Lakshmi Apartments, Sarai Kale Khan,New Delhi',
clientId: 'general',
clientName: 'Restaurant',
accessLevelId: 'sscaskoo31',
accessLevelName: 'basic',
departmentName: 'test',
departmentId: '58089a9c86337d1894ae1834',
employeeId: 'EMP1102',
employeeGrade: 'A',
employeeGradeId: '1221' }


Suggest what i am doing wrong?

Adding the code

var user=req.body;
// var hodId="";
if (req.body.clientId=="general") {
user.accessLevelName="basic";
}
if (!(req.body.departmentId==null || req.body.departmentId=="")) {
Departments.find({ '_id': req.body.departmentId },function(err, departments) {
// if there is an error retrieving, send the error. nothing after res.send(err) will execute
if (err) {
res.send(err);
}
console.log("department"+departments);
// user.hodId="test";
user.departmentName=departments.departmentName;
var newUser =new User(user);

newUser.save(function(err,obj) {
if (err) {
return res.json({success: false, msg: "User Name Already Exists"});
} else {
var token = jwt.encode(obj, config.secret);
res.json({success: true, token: 'JWT ' + token,msg: 'Successful created new user.',user:obj});
}
});
});
} else{
newUser.save(function(err,obj) {
if (err) {
return res.json({success: false, msg: "User Name Already Exists"});
} else {
var token = jwt.encode(obj, config.secret);
res.json({success: true, token: 'JWT ' + token,msg: 'Successful created new user.',user:obj});
}

Answer

The mongoose .find() method returns an Array, not an object. The output of console.log(departmants) is, or at least should be:

 [{ _id: 58089a9c86337d1894ae1834,
  departmentName: 'Software Engineering',
  clientId: '57ff553e94542e1c2fd41d26',
  hodName: 'Mr Shekar Krishna',
  noOfEmployees: 90,
  hodId: 'djekjakejkjkjekajk3j33',
  __v: 0 }]

Which means that to access what youre looking for you need to access the first object in the array first.

var hodId=departments[0].hodId;    

The devil is in the details.

Once you have that var you can then add it to another user

user.hodId = hodId;