2015-07-05 82 views
2

我有一個架構項目定義爲:的NodeJS應用獴數據庫,其中有條款加入

var ArticleSchema = new Schema({ 
    title: String, 
    content: String, 
    creator: { 
     type: Schema.ObjectId, 
     ref: 'User' 
    } 
}) 

和用戶模式:

var UserSchema = new Schema({ 
    type: String, //editor, admin, normal 

    username: String, 
    password: String, 

}) 

我需要查詢的編輯器,即創建的所有文章SQL語言

select Article.title as title, Article.content as content 
from Article inner join User 
on Article.creator = User._id 
where User.type = 'editor' 

這是我曾嘗試

exports.listArticle = function(req, res, next) { 
    var creatorType = req.query.creatorType 
    var criteria = {} 
    if (creatorType) 
     criteria = {'creator.type': creatorType} 
    Article.find(criteria).populate('creator').exec(function(err, articles) { 
     if (err) 
      return next(err) 
     //ok to send the array of mongoose model, will be stringified, each toJSON is called 
     return res.json(articles) 
    }) 
} 

返回articles是一個空數組[]

我也試過Article.populate('creator').find(criteria),也不會與工作的錯誤:

utils.populate: invalid path. Expected string. Got typeof `undefined` 
+1

如果每個用戶不會太多,您可以考慮將文章存儲在用戶集合中。看看這篇偉大的文章,它解釋瞭如何根據你的數據設計你的模式:http://blog.mongodb.org/post/87200945828/6-rules-of-thumb-for-mongodb-schema-design-part -1 – ZeMoon

+0

@ZeMoon讓我們說,如果我想通過createdDate訂購文章,那麼從用戶填充不會提高速度。 – OMGPOP

+0

那麼,你可以使用聚合框架。您可以通過多種方式爲數據建模,每種方式都有自己的優缺點。而且,多個查詢不一定是壞事。在sql數據庫連接導致相當多的處理開銷。 – ZeMoon

回答

1

沒有MongoDB中加入的概念,因爲它是一個不關係型數據庫。

填充方法實際上是Mongoose的一個功能,並在內部使用多個查詢來替換引用的字段。

這將必須使用多部分查詢完成,首先在User集合上,然後在Article集合上完成。

exports.listArticle = function(req, res, next) { 

    var creatorType = req.query.creatorType 
    var criteria = {} 
    if (creatorType) 
     criteria = {'type': creatorType} 

    User.distinct('_id', criteria, function (err, userIds) { 

     if (err) return next(err); 

     Article.find({creator: {$in: userIds}}).populate('creator').exec(function(err, articles) { 
      if (err) 
       return next(err) 
      //ok to send the array of mongoose model, will be stringified, each toJSON is called 
      return res.json(articles) 
     }) 
    }) 

} 
+0

我可以做一個查詢而不是2嗎?因爲我已經填充'creator' – OMGPOP

+0

人口在查詢後完成。您可以獲取每篇文章,填充用戶然後過濾它們(使用forEach()),但這會帶來太多的開銷。這是在MongoDB中處理引用的唯一方法。 – ZeMoon

+0

你的意思是如果我先填充然後查詢,我可以將它們合併成一個命令? – OMGPOP