2012-12-06 35 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) {...}); 
相关问题