2014-11-06 2 views
1
내가 다 대다 연관 관계로 두 모델에 봉착

: 사용자, 즉Sails.js, 워터와 합류

프로젝트 관리 : 사용자는 프로젝트와 프로젝트의 수에 속한다는 임의의 수에 속하는 사용자.

이제 특정 사용자 ID에 속한 모든 프로젝트를 검색하고 싶습니다. 이것을 어떻게 할 수 있습니까?

다음 쿼리는 배열이 users 인 데이터베이스에있는 모든 프로젝트를 반환합니다.이 프로젝트는 사용자가 발견되면 하나의 속성을 가지며, 다른 하나는 비어 있습니다.

Projects.find().populate('users',{id : my_user_id}); 

프로젝트 모델

module.exports = { 

    attributes: { 
    name : { 
     type : 'string', 
     maxLength : 80, 
     required : true 
    }, 
    users : { 
     collection : 'User', 
     via : 'projects' 
    }, 

    } 
} 

사용자 모델 : 당신은 채울 먼저 사용자를 찾을 수 ... 즉, 다른 방법으로 주위를 이동하고있다

var User = { 
    // Enforce model schema in the case of schemaless databases 
    schema: true, 

    attributes: { 
    firstname : { 
     type: 'string', 
     size : 60 
    }, 
    lastname : { 
     type: 'string', 
     size : 60 
    }, 
    email  : { 
     type: 'email', 
     unique: true, 
     required : true, 
     size : 80 

    }, 
    passports : { 
     collection: 'Passport', 
     via: 'user' 
    }, 
    projects : { 
     collection : 'Project', 
     via : 'users' 
    }, 
    toJSON: function() { 
     var obj = this.toObject(); 
     delete obj.passports; 
     delete obj.projects; 
     return obj; 
    } 
    } 
}; 
+0

모델 정의의 관련 부분을 게시해야합니다. – Meeker

답변

4

다음과 같은 프로젝트 제휴 :

User.findOne(userid) 
    .populate('projects') 
    .exec(function(err, projects) { 
     // projects for that user returned 
    }); 
0

@ Melvin의 솔루션은 훌륭하게 작동하지만 다음 작업을 수행 할 수도 있습니다.

Project.find({users: [my_user_id, second_user_id]}) 
.populate('users') 
.exec(function(err, projects) { 

});