2016-12-13 5 views
2

두 모델이 있습니다. 사용자와 채팅은 many to many 연관이 있습니다.URL/모델/<id>/연관을위한 돛의 중첩 된 연관을 자동으로 채우는 방법

의 user.js는

module.exports = { 

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

    email:{ 
     type : 'string' 
     ,email : true 
     ,required: true 
     ,unique : true 
    }, 
    enpassword : { 
     type: 'string' 
    }, 

    online : { 
     type: 'boolean', 
     defaultsTo: false 
    }, 

    socketid: { 
     type: 'string' 
    }, 
    chats : { 
     collection: 'chat', 
     via: 'users', 
     dominant: true 
    } 

}; 

Chat.js는

module.exports = { 
    attributes: { 
    messages : { 
     collection: 'message', 
     via  : 'chat', 
     dominant : true 
    }, 
    users : { 
     collection: 'user', 
     via  : 'chats' 
    }, 
    } 
}; 

나는 각 채팅의 채팅 있지만 사용자 협회의 목록을 얻고 돛 청사진/사용자/1/채팅 전화 채워지지 않습니다 .

Sails 쿼리에서 어떻게이 작업을 수행 할 수 있습니까?

+0

컨트롤러에서 '찾기'를 무시하고 쿼리에서'.populate ('users')'를 수행 했습니까? – Joey

+0

안녕하세요, Joey, URL에/user/1/chats에 1과 같은 동적 사용자 ID 값이 포함되어 있습니다. 대체 솔루션을 찾고 있습니다. –

답변

1

위대한 질문입니다. 이렇게하는 것이 정말 쉬운 방법입니다.

먼저 다음 모듈이 필요합니다.

var nestedPop = require('nested-pop'); 

다음으로 쿼리를 실행하십시오.

getPopulatedUsers = function(req, res) { 
    User.find() 
    .populate('chats') 
    .then(function(users) { 
    return nestedPop(users, { 
     chats: [ 
     'messages', 
     'users' // I actually wouldn't recommend populating this since you already have the users 
     ] 
    }).then(function(users) { 
     console.log(users); 
     res.json(users); 
    }); 
    }); 
} 

기타 문서는 다음 링크에서 찾을 수 있습니다. https://www.npmjs.com/package/nested-pop