javascript

时间:2016-05-28 12:15:09

标签: mysql node.js express

我正在使用expressjs和mysql包。 我有一个用户表,每个用户可以有许多技能,项目,证书存储在不同的表中。如何将所有这些数据放入单个用户对象中。

getUserDataById(req.params.id, function (user) {
  if (user) {
    res.send(user);     
  }
}
var getUserDataById = function (id, callback) {
  connection.query(userSql, id, function (err, rows) {
    if (rows[0]) {
      user = new User(rows[0]); //parse row data to user obj  
      // The main problem 
      //get skills and projects.... and asign to user obj
      parseArrayData(skillSql, user.id, Skill, function (skills) {
          user.skills = skills;
        }
      );
      parseArrayData(projectSql, user.id, Project, function (project) {
          user.projects = projects;
        }
      );
      // is here
      callback(user);
    }
  });
}
var parseArrayData = function (query, id, Obj, callback) {
  connection.pool.query(query, id, function (err, rows) {
    if (err) {
      throw err;
    } else {
      console.log('rows',rows);
      var array = [];
      for (var i = 0; i < rows.length; i++) {
        array[i] = new Obj(rows[i]); // map obj's attributes with fields
      };
      callback(rows);
    }
  });       
};

1 个答案:

答案 0 :(得分:0)

您可能有这些不同的表名称(假设):usersskillsprojectscertifications;

函数从db获取查询结果;

function executeQuery(tablename, userId, callback) {
  var sql = 'select * from ' + tablename + ' where id = ' + userId;
  connection.query(sql, function (err, rows) {
    if (err) { callback(err, null); }
    else { callback(null, rows); }
  })
}

将获取用户id的所有结果并返回json对象的函数;

 var getUserDataById = function (userId, callback) {
    executeQuery('users', userId, function(users) {
       executeQuery('projects', userId, function(projects) {
          executeQuery('skills', userId, function(skills) {
             executeQuery('certifications', userId, function(certifications) {
                var result = { // format you result.
                   id: userId,
                   users: users,
                   projects: projects,
                   skills: skills,
                   certifications: certifications
                };
                callback(result);
             }); 
          });
       });
    });
    callback(null);
 });

用法:

getUserDataById(req.params.id, function (user) {
  if (user) {
    res.send(user);     
  }
}