2013-08-24 40 views
2

我試圖在沒有任何運氣的情況下在Stackoverflow上找到任何類似的問題。我正在努力尋找創建兩個文檔之間關係的正確方法。這是一個非常簡單的分層分類案例。每個類別可以有一個父母和多個孩子。使用Mongoose在MongoDB中創建關係(在Node.js中)

var categorySchema = Schema({ 
    name: String, 
    parent: { type: Schema.ObjectId, ref: 'Category' }, 
    children: [{ type: Schema.ObjectId, ref: 'Category' }], 
    order: Number 
}); 

var Category = mongoose.model('Category', categorySchema); 

當我創建一個新的類別時,我得到了_id到(如果有的話)父級它應該有的。我將這個_id作爲POST/PUT請求中的字符串並使用此_id獲取類別。抓取工作正常,我得到正確的類別作爲結果。但這是我奮鬥的地方,我如何使用mongoose查詢返回的結果來創建新類別與其父類之間的關係?

var query = Category.find({'_id': parentCategoryID}); 
query.select('name'); 
query.exec(function (err, parentCategory) { 
    if (!err) { 
     console.log("Fetched parentCategory: "+parentCategory+".. parentCategory._id: "+parentCategory._id); 
     var parent = parentCategory.toObject(); 
     var category = new Category(); 
     category.name = name; 
     category.parent = Schema.ObjectId(parent._id); 

的console.log 擷取的parentCategory:{名: '父類別',_id: 5218dcd6e6887dae40000002} .. parentCategory._id:未定義

我試圖在多設置parent屬性不同的方式,我不能得到它的工作。還沒有找到關於這個問題的文件的運氣。

非常感謝任何幫助,我希望更多的人能從這個問題的答案中受益。

+1

對於像Neo4j這樣的圖形數據庫而言,這聽起來更像是一個像MongoDB這樣的面向文檔數據庫的工作。 – Philipp

+0

我真的不知道如何從我的問題中獲得足夠的信息來得出結論。類別部分只是實際數據模型的一小部分。然後,我還沒有對MongoDB的優點/缺點進行廣泛的研究,我選擇了MongoDB來學習新的東西。感謝您的輸入,但從未聽說過Neo4j。 – oehman

回答

1
//problem 1: `find` returns a list of results. You just need findById 
var query = Category.findById(parentCategoryID); 
query.select('name'); 
query.exec(function (err, parentCategory) { 
    //Problem 2: don't ignore errors. Handle them first and short-circuit return 
    if (err) { 
     console.err(err); 
     return; 
    } 
    console.log("Fetched parentCategory: "+parentCategory+".. parentCategory._id: "+parentCategory._id); 
    //problem 3: mongoose will do the right thing with your schema here 
    //all you need is 
    var category = new Category(); 
    category.name = name; 
    category.parent = parentCategory; 
    //and don't forget 
    category.save(...callback....); 
} 

另外請注意,如果你有一個模式,你指定的東西,不模式匹配,貓鼬將只是下降的數據,這可能是發生了什麼事給你,假設你在某些時候叫category.save()

+0

我刪除了錯誤處理,並保存爲了不膨脹我的問題的關鍵部分。顯然這些都存在。 你說得對,上面的代碼有效。我想我沒有測試這種方式來修復我的模式後分配parentCategory。 謝謝! – oehman

+0

不要忘記處理parentCategory爲空。 –