Answer the question
In order to leave comments, you need to log in
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 },
})
Answer the question
In order to leave comments, you need to log in
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 }
)
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 questionAsk a Question
731 491 924 answers to any question