简体   繁体   English

猫鼬模式扩展时间戳以具有新属性(用户名)

[英]Mongoose Schema extend timestamp to have new properties (username)

I´m using MongoDB and mongoose for a project that needs to track data creation and changes. 我在将MongoDBmongoose用于需要跟踪数据创建和更改的项目。 The requirements are that I need to keep track of records creation and changes including the date/time and the application user (not the OS user) who did it. 要求是我需要跟踪记录的创建和更改,包括日期/时间和执行此操作的应用程序用户 (而非OS用户)。

I´ve seen the mongoose timestamps option that would solve my date/time issue, but is there a way to extend it to include extra properties, where I´m gonna be adding the application username ? 我见过猫鼬时间戳选项可以解决我的日期/时间问题,但是有没有办法将其扩展为包括其他属性,我将在其中添加应用程序用户名?

If not, is there a single place where I can write a function that will be called on every creation/update so that I can include/modify these fields ? 如果没有,我是否可以在一个地方编写一个可以在每次创建/更新时调用的函数,以便我可以包括/修改这些字段?

Today I´m insering these properties on every model like below, but I would like to move all of them to a single place. 今天,我在下面的每个模型中插入了这些属性,但我想将它们全部移动到一个地方。

var companySchema = mongoose.Schema({

    name: {
        type: String,
        index: true
    },
    phone: {
        type: String
    },
    deleted: {
        type: Boolean
    },
    createdAt: {
        type: Date
    },
    createdBy: {
        type: String
    },
    updatedAt: {
        type: Date
    },
    updatedBy: {
        type: String
    }
});

How would be the best approach for it ? 最好的方法是什么?

I would approach it by creating two models, one for each Data created , one for each Data Changes . 我将通过创建两个模型来实现它, 每个创建的数据一个模型, 每个数据更改一个模型。

Data created which will have 6 fields one is createdBy , createdAt , and one will be a field with an array of reference id of Data Changes, deletedBy , deletedAt , deletedFlag . 创建这将有6个字段之一是createdBy,createdAt,以及一个将与数据的变化,deletedBy,deletedAt,deletedFlag参考ID的阵列的场数据。

Data Changes will have fields dataID which will have reference id of data created, updatedBy and updatedAt . 数据更改将具有字段dataID ,该字段将具有创建, updatedByupdatedAt数据的引用ID。

This way it will be easy to keep track of when it was created when it was changes and when it was deleted. 这样,很容易跟踪创建时间,更改时间和删除时间。

PS: You can remove either of Array in Data created model or dataID ref id in Data Change mode, it was just me being extra cautious while binding. PS:您可以删除Data创建模型中的Array或Data Change模式中的dataID ref id,这只是我在绑定时要格外小心。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM