从各种 Sails.js 模型协会中获得扁平化 JSON

Get a flatten JSON from an various Sails.js models associations

我有这个层次结构:Person < has a > Team < has a > Department

我想从这样的人那里提取扁平化记录:

{ 
  "name": "Foo",
  "id": 1,
  ...
  "team": {
    "name": "MGMT",
    "id": 1,
    "department": 1
    ...
  },
  "department": {
    "name": "Top",
    "id": 1,
    "office": 1
    ...
  }
}

这些是模型:

个人

// A person that belongs to a team
module.exports = {

  attributes: {
    name: {
      type: 'string',
      required: true
    },

    //Assosiations    
    team: {
      model: 'team'
    },
    department: {
      model: 'department',
      via: 'team.department'
    }, 
  }
};

团队

// A team with many persons and belongs to one department
module.exports = {

  attributes: {
    name: {
      type: 'string',
      required: true
    },

    //Associations
    department: {
      model: 'department'
    },

    members: {
      collection: 'person',
      via: 'team'
    }
  }
};

部门

// A department that has many teams
module.exports = {

  attributes: {
    name: {
      type: 'string',
      required: true
    },

    teams: {
      collection: 'team',
      via: 'department'
    }
  }
};

我不能这样做(是的,它有更多级别):

function (req, res) {

        Person.findById(1).exec(function (err, people) {
            Team.findById(people[0].team).exec(function (err, teams) {
                Department.findById(teams[0].department).exec(function (err, departments) {
                    Office.findById(departments[0].office).exec(function (err, offices) {
                        Company.findById(offices[0].company).exec(function (err, companies) {

                            var composeRecord = Object.assign(
                                people[0], {
                                    team: teams[0],
                                    department: departments[0],
                                    office: offices[0],
                                    company: companies[0],
                                });

                            res.send(composeRecord);

                        })
                    })
                })
            })
        })  
    }

有什么办法可以做得更好吗?

如果您正在使用 Mongo,您可以使用 promises 来完成。会好看很多

var composeRecord
Person.findById(1).then(function(people){
    composeRecord = people[0]
    return Team.findById(people[0].team)
}).then(function (teams) {
    composeRecord.team = teams[0]
    return Department.findById(teams[0].department)
}).then(function(departments){
    composeRecord.department = departments[0]
    return Office.findById(departments[0].office)
}).then(function(offices){
    composeRecord.office = offices[0]
    return Company.findById(offices[0].company)
}).then(function(companies){
    composeRecord.company = companies[0]
    res.json(composeRecord)
}).catch(function (err) {
    console.log(err)
})

如果你正在使用像 MySQL o PG 这样的相关数据库,你应该写一个 query