将自定义属性添加到水线模型

时间:2016-06-06 09:51:55

标签: javascript node.js sails.js

由于嵌套填充不可用,我需要手动传递我的自定义属性。在我的具体情况中,这意味着:客户有很多项目,项目有很多贡献者。

Customer.find().populate('projects').exec(function(err, customer) {

回复看起来像

[
    {
        "projects": [
            { "name": "First project" }
        ],
        "customer": "John Doe"
    },
    {
        "projects": [
            { "name": "Another project" },
            { "name": "And another one" }
        ],
        "customer": "Susan Doe"
    }
]

我正在遍历项目并希望附加contributors属性。我试过了

customer.forEach(function(customer, index) {
    customer.projects.forEach(function(project, index) {
        ProjectContributor.find({
            project: project.id
        }).exec(function(err, contributor) {
            project.contributors = contributors;
        });

project.contributors仍未定义。为什么?以及如何附加这些自定义属性?

1 个答案:

答案 0 :(得分:-1)

您的代码中存在许多错误。

Customer.find().populate('projects').exec(function(err, customers) {
  customers.forEach(function(customer, index) {
    customer.projects.forEach(function(project, index) {
      ProjectContributor.findOne({project: project.id}) // use findOne since you only want one project at a time
      .populate('contributors')
      .exec(function(err, projectContributor) {
        project.contributors = projectContributor.contributors; // contributors is in projectContributor
      });
    });
  });
});