2013-01-04 42 views
0

在Node.js + Mongoose中,我想在集合文章中找到一些用戶的評論。如何設計mongoDB的模式

設計1:

articles: 
{ 
    ... 
    users: ["[email protected]","[email protected]","[email protected]"] 
    comments: [ 
     {email:"[email protected]", comment:"..."}, 
     {email:"[email protected]", comment:"..."}, 
     {email:"[email protected]", comment:"..."}, 
     ... 
    ] 
} 

設計2:

articles: 
{ 
    ... 
    comments: [ 
     {email:"[email protected]", comment:"..."}, 
     {email:"[email protected]", comment:"..."}, 
     {email:"[email protected]", comment:"..."}, 
     ... 
    ] 
} 

我使用的設計1,首先找到{用戶:req.query.user},然後從檢索結果中的用戶的評論。但我覺得它不聰明。有沒有像解決方案2的方式,我不知道如何編寫數據庫查詢。

回答

0

您對第二個結構的查詢實際上會同樣簡單。在蒙戈外殼那就是:

db.collection_name.find({'comments.email': '[email protected]'})

查詢引擎是足夠聰明,自省數組並返回兌現要求的文件。

從這一點開始,您只需遍歷應用程序代碼中的註釋並使用匹配的電子郵件提取註釋。如果這是您構建數據的方式,則無需在查詢時進行此限制。根據需要循環所有註釋。

如果將結果集限制爲僅針對特定用戶的評論很重要,那麼您可以重新考慮將您的對象構建爲更關係型的某種方式(可能是與每篇文章集關聯的每條評論的文檔?)嘗試根據查找潛力的重要價值來考慮您的模式,並在可能的地方對其進行索引。

+0

感謝您的幫助。我使用mongoose,find({comments.email:req.query.user}出現錯誤:SyntaxError:意外的令牌。 at Module._compile(module.js:437:25) at Object.Module._extensions .. js(module.js:467:10) at Module.load(module.js:356:32) – blackgun

+0

查詢語法不應該有任何問題,所以它必須與Mongoose如何處理查詢構造有關。記錄時'req.query.user'的價值是什麼? – DeaconDesperado

+0

req.query.user = [email protected],Article是一個模型,在我的app.js中,代碼是:Article.find({comments。電子郵件:req.query.user} – blackgun