2014-10-12 10 views
5

Ich schreibe diese Frage und die Antwort in der Hoffnung, es wird jemand anderem helfen (oder wenn es eine bessere Antwort gibt).Mongoose subschema array virtuals

Wie erstelle ich virtuals für Mongoose geschachtelte Schemas, wenn in Array-Form?

Hier sind die Schemata:

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

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

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

Wie ich eine virtuelle auf variations möchte. Es scheint, dass, wenn die Unter doc kein Array ist, dann können wir einfach tun:

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

Aber das funktioniert nur für nicht-Arrays.

Antwort

4

Der Schlüssel ist, das virtuelle als Teil des Teilschemas und nicht als übergeordnetes Element zu definieren, und es muss vor das Teilschema wird übergeordneten zugeordnet werden. Der Zugriff auf das übergeordnete Objekt kann über 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] 
    } 
}); 
erfolgen