在javascript中将元素添加到现有JSON

时间:2016-10-20 10:54:44

标签: javascript json node.js

您好我有以下JSON命名部门。当我做console.log(部门)时,我得到了这个。

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

但是当我尝试将像hodId这样的值赋给像这样的变量时。

var hodId = departments.hodId;

然后执行console.log我得到了未定义。

另外我需要添加这个值" hodId"转到另一个JSON"用户"目前是这样的:

{ 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' }

建议我做错了什么?

添加代码

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});
    }

1 个答案:

答案 0 :(得分:1)

mongoose .find()方法返回一个数组,而不是一个对象。 console.log(departmants)的输出是,或者至少应该是:

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

这意味着要访问您要查找的内容,您需要先访问阵列中的第一个对象。

var hodId=departments[0].hodId;    

获得var后,您可以将其添加到其他用户

user.hodId = hodId;