将选项传递给mongoose schema toJSON transform inline(在expressjs中)?

时间:2015-06-04 15:45:42

标签: express mongoose

我有一个mongoose(3.1)'Thing'架构,其toJSON我可以通过以下方式自定义...

Thing.options.toJSON = {};
Thing.options.toJSON.transform = function (doc, ret, options){
  // do something to ret, depending on options                                                                                                                                                                                
}

如代码注释中所述,我想在给定选项值的情况下更改JSON表示。我想在快递行动中传递这些选项,也许......

app.get(..., function (req ,res){
  Thing.find({}, function(err, things){
    var myOptions = {...} // something application stateful
    return response.send(things) // MAYBE ADD OPTIONS HERE?
  });
});

如何修改expressjs以允许我提供选项?

谢谢,

2 个答案:

答案 0 :(得分:0)

恕我直言,接受的答案(@ VladStirbu' s)是错误的,因为选项是在架构级别设置的。它正在更改架构,因此即使您没有明确请求,这些选项也可以在后续调用中使用。

应该为该调用单独设置 inline 选项:

使用快递定期通话:

app.get(..., function (req ,res){
  Thing.find({}, function(err, things){
    return response.send(things);
  });
});

使用express调用,但将内联选项传递给toJSON():

app.get(..., function (req ,res){
  Thing.find({}, function(err, things){

    let toJSONOptions;  // may be undefined, it's fine
    if ( /* whatever condition you decide */ ) {
      // this keeps the schema's original options:
      toJSONOptions = Object.assign({ }, Thing.schema.options.toJSON);
      // request to use original transform function, if any:
      toJSONOptions.transform = true;
      // set your own options to be passed to toJSON():
      toJSONOptions._options = {...}; // whatever you need here
    }

    return response.send( things.map(e => e.toJSON(toJSONOptions)) );
  });
});

toJSONOptions = undefined没问题,就像对toJSON()的常规通话一样,这是字体化时表达的内容。

如果您正在使用findOne()findById(),那么只需返回:

    return response.send( thing.toJSON(toJSONOptions) );

这是让我想到这个的Mongoose提交: https://github.com/Automattic/mongoose/commit/1161f79effc074944693b1799b87bb0223103220

答案 1 :(得分:-1)

您可以通过将选项传递给架构选项来传递路由处理程序中的选项:

app.get(..., function (req ,res){
  Thing.find({}, function(err, things){
    Thing.schema.options.toJSON.myOptions = {...} // something application stateful

    return response.send(things) // MAYBE ADD OPTIONS HERE?
  });
});

这样,选项将在transform函数中作为options对象的属性提供:

Thing.options.toJSON.transform = function (doc, ret, options){
  console.log(options.myOptions); // prints the app specific data provided earlier                                                                                                                                                                           
}