2012-10-15 46 views
6

我正在使用Mongoose 3.x來實現樹結構(類似於Mongo文檔中的這個),但我不確定封裝的最佳方式所有用於一般加載具有其兄弟和祖先的特定節點的邏輯,以及具體如何最好地使用與ref相同的集合中的羣體功能。Mongoose.js:如何通過人口實現樹結構

對於某些上下文,我正在使用的樹中沒有對節點進行編輯,但可能隨時將新的子節點添加到任何節點。到目前爲止,我已經用一組模型方法正常工作,它們在初始查找之後加載對象,但似乎應該有一種更好的方法來輕鬆加載單個分支,並將所需的所有父級和同級數據加載到單個分支命令在控制器中,並將所有相關總體封裝在模型上的一些方便的查找方法中。

我想與之合作的基本模式,那麼,可能會(在這裏也可以:https://gist.github.com/3889616):是這樣的

// Sub-document to store parent ref along with it's value (a form of caching) 
var Parent = new Schema({ 
    id: ObjectId 
    , text: String 
}); 

// Main tree-node element schema 
var Branch = new Schema({ 
    text: { 
     type: String 
     , required: true } 
    , date: {type: Date, default: Date.now } 
    , trail: [Parent] 
    , parentBranchId: ObjectId 
    , parentBranch: { type: Schema.Types.ObjectId, ref: 'Branch' } 
    , _children: [{type: Schema.Types.ObjectId, ref: 'Branch'}] 
    // These two have been commented out because I have no clue how to best implement 
    // , _priorSiblings: { type: Schema.Types.ObjectId, ref: 'Branch' } 
    // , _followingSiblings: { type: Schema.Types.ObjectId, ref: 'Branch' } 
}); 

我希望然後將能夠加載分支W /通過類似下面的代碼相關的相關數據,但在這一點上我幾乎喪失,可能是一個很好的協議關閉基地:

req.app.models.Branch 
    .findById(req.param("id")) 
    .populate("parentBranch") 
    .populate("parentBranch._children") 
    .exec(...) 

最終,我很想有我的東西可以放棄t插入到Mongoose的「樹」插件中,但我想我必須先正確地構建這個架構。有任何想法嗎?

FWIW,在一天結束時,我真正需要每個分支的數據是父母,下一個兄弟姐妹,以前的兄弟姐妹(無論是在創建時間方面)還是父母的所有孩子。

在此先感謝!

回答