2012-12-20 79 views
2

我有這樣低於此示出的一些集合持有關係,testMastertestDoc之間關係握持testDocMaster獲取從多個集合的數據在蒙戈

對於例如內:

testMaster { 
_id: "Schema.Objectid", 
name: "String" //master name 
} 

testDoc { 
_id : Schema.ObjectId, 
name: "String", //doc name 
other datas 
} 

testDocMaster { 
masterId: "_id of the testMaster table", 
docId : "_id of the above testDoc" 
} 

對於每個主入口,我們預計有很多關係,

什麼是如果我有masterId,則從testDoc表中獲取數據的最佳方法。

+0

關係集合通常是MongoDB中的一種反模式。當你有一個n:m的關係時,你應該添加一個數組字段到其中一個文件,它保存着對另一個文件的引用。我知道,當你習慣於關係數據庫時,這聽起來很不直觀。但MongoDB不是關係數據庫。 – Philipp

+1

@ Philipp,這根本不是一個準確的說法。一些關係最好表現爲嵌入式數組,一些最好的表現形式是鏈接的獨立集合。請參閱我的答案在這裏解釋http://stackoverflow.com/questions/13897305/how-would-you-model-customer-order-ordertem-product-in-nosql-database/13898439#13898439 –

回答

0

假設你testDocMaster架構使用ObjectId類型ref你可以使用貓鼬的query population支持其他兩個集合,以幫助這一點:

TestDocMaster.findOne({ masterId: masterId}) 
    .populate('docId') 
    .exec(function(err, testDocMaster) { 
     // testDocMaster.docId is populated with the full testDoc for the 
     // matching _id 
    }); 
1

我得到它的工作使用這樣的:

// GLOBAL ARRAYS FOR STORING COLLECTION DATA 
var collectionOne = []; 
var collectionTwo = []; 
app.get('/', function(req, res){ 
    MongoClient.connect("mongodb://localhost:27017/michael", function(err, db) { 
    if(!err) { 
     console.log("We are connected"); 
    } 
    db.collection("collectionOne", function(err, collection) { 
     collection.find().sort({order_num: 1}).toArray(function(err, result) { 
     if (err) { 
      throw err; 
     } else { 
      for (i=0; i<result.length; i++) { 
      collectionOne[i] = result[i]; 
      } 
     } 
     }); 
     db.collection("collectionTwo", function(err, collection) { 
     collection.find().sort({order_num: 1}).toArray(function(err, result) { 
      if (err) { 
      throw err; 
      } else { 
      for (i=0; i<result.length; i++) { 
       collectionTwo[i] = result[i]; 
      } 
      } 
     }); 
     }); 
     // Thank you aesede! 
     res.render('index.html', { 
     collectionOne: collectionOne, 
     collectionTwo: collectionTwo 
     }); 
    }); 
    }); 
}); 

現在,由於某些原因,當節點重新啓動時,我點擊刷新,它不會將HTML呈現到前端。但是,任何後續刷新都會正確呈現頁面。