Add Created By, Updated By, Created Date, Updated Date to Model via Mixin in Loopback

Sunil K Samanta
2 min readSep 6, 2018

Adding a created by, created date and updated by, updated date is always needed in Models. So why don’t we use a common Mixin for that.

We’ll create a Mixin which will do the job for your Models without copying and pasting the same code in every model.

READ =:> MySql Like Auto Increment Numeric Primary Key For Loopback with MongoDB

Create a file named “created-modified-injection.js” in common/mixins/ folder. and add the bellow code

//created-modified-injection.jsmodule.exports = function(Model, options) {
'use strict';
Model.defineProperty('created_by', {type: Number});
Model.defineProperty('updated_by', {type: Number});
Model.defineProperty('created_date', {type: Date});
Model.defineProperty('updated_date', {type: Date});
Model.observe('before save', function event(ctx, next) {
const token = ctx.options && ctx.options.accessToken;
const userId = token && token.userId;
let date = new Date();
if (ctx.instance) {
if (ctx.isNewInstance) {
ctx.instance.created_by = ctx.instance.created_by || userId;
ctx.instance.created_date = date;
}else{
ctx.instance.updated_by = ctx.instance.updated_by || userId;
ctx.instance.updated_date = date;
}
}
next();
});
};

This Will add created_by, created_date at the time of creating a new instance of the model and will add updated_by, updated_date while updating the instance in every model you enable the mixin in.

Now Enable the Mixin in the Model by adding the bellow property in your model.json files

"mixins": {
"CreatedModifiedInjection": true
},

That’s all! Comment if you have anything in mind.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Sunil K Samanta
Sunil K Samanta

Written by Sunil K Samanta

Harmoniously blending technology, mindfulness, music, and travel. My journey is fueled by the vision of a more interconnected and compassionate world.

No responses yet

Write a response