1

I'm using Sails beta 0.10.0-rc7 and I'm having troubles with model associations. I have the following scheme:

Document - has - Attributes -- have -- Type

Documents that have attributes, which have a Type. I'm trying to retrieve the whole structure from only one query using populate:

        var query = model.findOne({id: id});

    for (var i = 0; i < model.associations.length; i++) {
        query = query.populate(model.associations[i].alias);
    }

With that code I can get the 1st level of the Model populated:

    res = {
        id: 1,
        name: '....',
        desc: '....',
        // This is populated
        attributes: [{
                id: 1,
                name: '...',
                // THIS Should be populated also!
                type: 1
                // Should be 
                // type: { id: 1, name: '....' .... }

            }
        ]

    }

How could I get the 2nd level of hierarchy (Type) ?

Thanks in advance :_)

josec89
  • 1,932
  • 1
  • 16
  • 19
  • I think this is answered in another page: http://stackoverflow.com/questions/23446484/sails-js-populate-nested-associations?rq=1 – josec89 Jun 02 '14 at 13:46

1 Answers1

0

You can use the built-in Blue Bird Promise feature to make it. (Working on Sails@v0.10.5)

UserMenuSection.find({
    userRole: userRole,
    type: type
  })
  .sort('orderId asc')
  .populate('items', {
    sort: 'orderId asc'
  })
  .then(function(values) {
    var ids = [];
    _.forEach(values, function(section) {
      _.forEach(section.items, function(item) {
        ids.push(item.id);
      });
    });
    var subItems = UserMenuItem.find({
      Parent: ids
    }).then(function(subItems) {
      return subItems;
    });
    return [values, subItems];
  })
  .spread(function(values, subItems) {
    var subItems = _.groupBy(_.sortBy(subItems, 'orderId'), 'Parent');
    var userMenu = _.map(values, function(section) {
      _.map(section.items, function(item) {
        item.subItems = subItems[item.id];
        return item;
      });
      return section;
    });
    res.json(userMenu);
  })
  .catch(function(err) {
    if (err) {
      var errMsg = "some error messages...";
      sails.log.error(errMsg);
      return res.serverError(errMsg);
    }
  });
Fermin Yang
  • 596
  • 4
  • 6