1

Im trying to query a deep association using sails js. In my example i have a one to many association between room and users and also a one to many association between user and pictures. My concern is if this is the correct way to assign pictures to users and also how can i map each collection of pictures to the corresponding user. Thanks.

// RoomController

show: function(req, res) {

    async.auto({

      room: function(cb) {
        var slug = req.param('slug');

        Room
          .findOneBySlug(slug)
          .populate('users', { where: { is_active: true, is_online: true } })
          .populate('messages', { limit: 30, sort: 'createdAt DESC' })
              .exec(cb)
      },

      pictures: ['room', function(cb, results) {
        if (!results.room) return res.badRequest('User not found.');

        Picture
          .find({user: _.pluck(results.room.users, 'id')})
          .where({'is_primary': true})
          .exec(cb);
      }],

      map: ['pictures', function(cb, results) {
        var room = results.room.toJSON();

        room.users = room.users.map(function(user) {
          user.pictures = results.pictures;
          return user;
        });
        return cb(null, room);
      }]

  },

     function finish(error, results) {
       if (error) return res.serverError(error);

       console.log(results.map)
     }

  );

}
adavia
  • 413
  • 5
  • 18
  • I couldn't get your question clearly. But if you are facing problem to do nested populate in sails then may be you can look into this question. Thought the title says many to many it actually is a scenario that involves one to many association. http://stackoverflow.com/questions/30324302/sails-js-complex-many-to-many-association – taufique May 21 '15 at 05:49
  • Refer to this thread for your answer. http://stackoverflow.com/questions/31562861/deep-associations-in-sails-mongo-using-populate-method/41751568#answer-41751568 – Clay Risser Jan 19 '17 at 20:58

0 Answers0