【问题标题】:Is there a way to use Mongoose middleware with the query builder?有没有办法将 Mongoose 中间件与查询构建器一起使用?
【发布时间】:2012-11-24 23:08:52
【问题描述】:

这就是我想要做的。

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

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

我知道我可以在一个模型一个模型的基础上通过静力学来实现这一点,但我想在每个模型上普遍这样做。有什么建议吗?

【问题讨论】:

  • 显然,添加到原型是实现此目的的方法。脏不脏我想是时候潜入水中了。

标签: node.js mongodb mongoose


【解决方案1】:

您可以通过创建一个简单的 Mongoose 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) {...});

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-20
      • 1970-01-01
      • 2018-03-15
      • 2016-11-01
      • 1970-01-01
      • 2018-09-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多