2012-12-06 6 views
5

ここに私がやろうとしていることがあります。質問ビルダーでMongooseミドルウェアを使用する方法はありますか?

mongoosejsを信頼できる環境で使用しています(別名は常に安全であるとみなされています)。私は実行するすべてのクエリに対して「select」と「populate」を渡す必要があります。私はすべての要求に対して一貫した方法でこれを取得しています。

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

あなたは、あなたがそれを適用したい任意のスキーマにmyFindmyFindOne機能を追加し、簡単なマングースplugin作成することによってこれを行うことができます:だから明らかに、プロトタイプに追加することでこれを行う方法である

// 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) {...});