2014-10-12 3 views
5

나는이 질문이 도움이 될 것입니다 희망의 대답을 게시하고 다른 사람 (또는 더 나은 대답을있을 경우).몽구스 하위 스키마 배열 virtuals에

어떻게 배열 형태로 몽구스 중첩 된 스키마에 대한 virtuals에를 만드는 방법?

var Variation = new Schema({ 
    label: { 
    type: String 
    } 
}); 

var Product = new Schema({ 
    title: { 
    type: String 
    } 

    variations: { 
    type: [Variation] 
    } 
}); 

내가 variations에 가상 싶습니다 방법 :

다음은 스키마입니다. 하위 문서가 배열이 아닌 경우 다음과 같이 간단하게 처리 할 수 ​​있습니다.

Product.virtual('variations.name')... 

하지만 비 배열에서만 작동합니다.

답변

4

핵심은 부모가 아닌 하위 스키마의 일부로 가상을 정의하는 것이며 보다 먼저 하위 키를 할당해야합니다. 부모 개체에 대한 액세스는 this.parent() :

var Variation = new Schema({ 
    label: { 
    type: String 
    } 
}); 

// Virtual must be defined before the subschema is assigned to parent schema 
Variation.virtual("name").get(function() { 

    // Parent is accessible 
    var parent = this.parent(); 
    return parent.title + ' ' + this.label; 
}); 


var Product = new Schema({ 
    title: { 
    type: String 
    } 

    variations: { 
    type: [Variation] 
    } 
}); 
을 통해 수행 할 수 있습니다.