Mongoose + Express - 将用户保存在文档中的正确方法是什么(审计信息)

时间:2012-08-02 09:05:13

标签: node.js express mongoose

我正在编写一个使用Mongoose ODM的Express.js应用程序。 创建/更新文档时,我希望它自动填充一些字段:

  • createdBy
  • createdOn

在我看来,实现的正确位置将在Mongoose插件中,该插件使用这些属性扩充文档,并提供默认值和/或mongoose中间件来填充字段。

但是,我完全不知道如何在插件中从会话中获取用户名。 有什么建议吗?

/**
 * A mongoose plugin to add mandatory 'createdBy' and 'createdOn' fields.
 */
 module.exports = exports = function auditablePlugin (schema, options) {
   schema.add({
     createdBy: { type: String, required: true, 'default': user }
   , createdOn: { type: Date, required: true, 'default': now }
   });
 };

 var user = function(){
   return 'user'; // HOW to get the user from the session ???
 };

 var now = function(){
   return new Date;
 };

1 个答案:

答案 0 :(得分:0)

你不能这样做,因为user函数被添加为此模式的原型方法。特别是它是独立的请求/响应。然而,有一个黑客。如果您有obj类型的对象schema,则可以执行

obj.session = req.session;
请求处理程序中的

。然后,您可以从该功能访问该会话。但是,这可能导致其他问题(例如在此集合上运行cron作业),对我来说,它看起来像是一个非常糟糕的练习。

您可以手动执行此操作,当前用户创建此架构对象时,不是吗?或者创建静态方法:

MySchema.statics.createObject = function ( user ) {
    // create your object
    var new_object = MySchema( ... );
    // set necessary fields
    new_object.createdBy = user.username;
}