L
L
Lexx Xell2022-03-18 16:32:03
JavaScript
Lexx Xell, 2022-03-18 16:32:03

How to properly make createdAt, changedAt and lastActivityAt fields for model in mongoose?

The model should have fields with the date it was created, the date it was modified, and the date of the last activity (the date the instance was last accessed). How to implement it in SQL I represent. How can you do this with MongoDB?

Model

const someSchema = mongoose.Schema({
    createdAt: { type: Date, default: Date.now },
    changedAt: { type: Date, default: Date.now },
    lastActivityAt: { type: Date, default: Date.now },
})


I will refrain from expressing my thoughts about the implementation, tk. js is not my main language, and I would like to see the opinion of experts.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
Lexx Xell, 2022-03-18
@LexxXell

For the createdAt and changedAt fields, I found a solution.
Mongoose 4+ supports automatic generation of the above fields. The schema will change like this:

const someSchema = mongoose.Schema(
    {
        lastActivityAt: { type: Date, default: Date.now },
    },
    { timestamps: true }
)

Regarding the lastActivityAt field, I did not find an elegant way, and it will have to be updated "manually" in the code when accessed. It would be possible to use the pre and post methods, but in a particular case this is not suitable, because it is not necessary to change the lastActivityAt field with every call, I only need to do it for specific functions.
My solution is to get an instance like this:
const instance = await someModel.findOne( <FilterQuery> )
    ? await someModel.findOneAndUpdate(
        <FilterQuery>,
        { lastActivityAt: Date.now() }
    )
    : await someModel.create( <ObjectQuery> );

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question