Search code examples
node.jsmodelhookloopbackjsstrongloop

SLC Loopback: Using model instance from within a model hook


With loopback model hooks, I know you can get access to an instance of a model like User before it is created by using beforeCreate:

User.beforeCreate = function(next, userInstance) {
  //your logic goes here using userInstance
  next();
};

But if I need to add some application logic that uses the firstName of the User that was just created, how would I do that?

User.afterCreate = function(next) {
  //I need access to the user that was just created and some of it's properties
  next();
};

Is there a way to get a hold of the user that has just been created or do I need to change my app logic to use before instead of after?


Solution

  • You can get access to the updated/created model instance via 'this':

    User.afterCreate = function(next) {
      var user = this;
      console.log("User created with id: " + user.id)
      next();
    };