2012-12-06 36 views
5

這就是我想要做的。我在一個值得信賴的環境中使用mongoosejs(也就是傳遞的東西總是被認爲是安全的/預先驗證過的),我需要通過它來選擇和填充潛在每一個我運行的查詢。我爲每個請求都以一致的方式獲取此信息。我想要做這樣的事情:有沒有辦法在查詢生成器中使用Mongoose中間件?

var paramObject = sentFromUpAbove; // sent down on every Express request 
var query = {...} 
Model.myFind(query, paramObject).exec(function(err, data) {...}); 

我會傳遞到中間件或其他結構的功能很簡單,只需:

function(query, paramObject) { 
    return this.find(query) 
    .populate(paramObject.populate) 
    .select(paramObject.select); 
} 

與同爲一個findOne。我知道如何通過直接延伸Mongoose來做到這一點,但這感覺很髒。我寧願使用中間件或其他構造,以乾淨的,有點未來的方式做到這一點。

我知道我可以通過靜態模型完成這個模型的基礎上,但我想在每個模型上普遍做到這一點。有什麼建議?

+0

因此很明顯,增加了原型是做到這一點的方式。髒或不是我想是時候潛入了。 –

回答

0

您可以執行類似於this的操作,但不幸的是,查找操作不會調用prepost,因此它們會跳過中間件。

0

您可以通過創建一個簡單的貓鼬plugin,增加了myFindmyFindOne功能,你希望它適用於任何架構做到這一點:

// Create the plugin function as a local var, but you'd typically put this in 
// its own file and require it so it can be easily shared. 
var selectPopulatePlugin = function(schema, options) { 
    // Generically add the desired static functions to the schema. 
    schema.statics.myFind = function(query, paramObject) { 
     return this.find(query) 
      .populate(paramObject.populate) 
      .select(paramObject.select); 
    }; 
    schema.statics.myFindOne = function(query, paramObject) { 
     return this.findOne(query) 
      .populate(paramObject.populate) 
      .select(paramObject.select); 
    }; 
}; 

// Define the schema as you normally would and then apply the plugin to it. 
var mySchema = new Schema({...}); 
mySchema.plugin(selectPopulatePlugin); 
// Create the model as normal. 
var MyModel = mongoose.model('MyModel', mySchema); 

// myFind and myFindOne are now available on the model via the plugin. 
var paramObject = sentFromUpAbove; // sent down on every Express request 
var query = {...} 
MyModel.myFind(query, paramObject).exec(function(err, data) {...}); 
相關問題