有没有办法将Mongoose中间件与查询构建器一起使用?

时间:2012-12-06 20:16:47

标签: node.js mongodb mongoose

这就是我想要做的事情。

我在一个受信任的环境中使用mongoosejs(也就是传递的内容总是被认为是安全的/预验证的)我需要在我运行的每个查询中传递“select”和“填充”内容。我对每个请求都以一致的方式得到这个。我想做这样的事情:

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来做到这一点,但这感觉很脏。我宁愿使用中间件或其他一些构造,以一种干净的,有些未来的方式来做到这一点。

我知道我可以通过模型逐个模型来完成这个,但我想在每个模型上普遍地做到这一点。有什么建议吗?

2 个答案:

答案 0 :(得分:0)

您可以执行与this类似的操作,但遗憾的是,查找操作不会调用prepost,因此他们会跳过中间件。

答案 1 :(得分:0)

您可以通过创建一个简单的Mongoose plugin来执行此操作,该{3}}将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) {...});