gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 02:42:58 25 4
gpt4 key购买 nike

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

  • 创建者
  • 创建于

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

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

/**
* 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;
};

最佳答案

你不能这样做,因为 user 函数被添加为该架构的原型(prototype)方法。特别是它是独立于请求/响应的。然而有一个黑客。如果您有 schema 类型的对象 obj,那么您可以这样做

obj.session = req.session;

在请求处理程序中。然后您可以从该函数访问 session 。然而,这可能会导致其他问题(例如在此集合上运行 cron 作业),对我来说这似乎是一种非常糟糕的做法。

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

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

关于node.js - Mongoose + Express - 在文档中保存用户的正确方法是什么(审核信息),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11774273/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com