2015-09-06 71 views
3

可以說我有一個評論模式。評論可以有幾個回覆。我如何創建一個虛擬屬性來轉換每個回覆的日期,如created_at?我不知道如何用對象子文檔結構數組來做到這一點。mongoose虛擬數組中的子文檔

回答

3

你需要seperately定義您子:

var Reply = new mongoose.Schema({ 
    body: String, 
    created_at: { 
    type: Date, 
    default: Date.now 
    } 
}); 

// Virtual must be defined before the subschema is assigned to parent schema 
Variation.virtual("created_at").get(function() { 
    // Parent is accessible 
    // var parent = this.parent(); 
    return moment(this.created_at).format('lll'); 
}); 


var Comment = new mongoose.Schema({ 
    body: String, 
    replies: { 
     type: [Reply] 
    } 
}); 

我編輯的代碼示例,也發現an issue on mongoose