Dakotah North
Dakotah North

Reputation: 1344

Referencing a property on a model with node.js in Loopback

Trying to very reference a property in with loopback and considering how much time I have tried to do this, I am clearly missing some fundamental concept.

Very simply, I have a Question model which has a points as a integer property and what I would like to do is simply print out the points property to the console.

module.exports = function(Question) {
    Question.observe('after save', function(ctx, next) {
    console.log(Question.prototype.points)
    next();
  });
};

When I do the above, it prints out undefined

Considering that this is such a simple operation to do, what am I missing?

json file:

{
  "name": "Question",
  "plural": "Questions",
  "base": "PersistedModel",
  "idInjection": true,
  "options": {
    "validateUpsert": true
  },
  "properties": {
    "text": {
      "type": "string",
      "required": true
    },
    "points": {
      "type": "number",
      "required": true
    }
  },
}

Upvotes: 1

Views: 136

Answers (1)

A.Z.
A.Z.

Reputation: 1648

You are almost there. Use context object that you get on after save.

module.exports = function(Question) {
  Question.observe('after save', function(ctx, next) {
    console.log(ctx.instance.points);
    next();
  });
};

Operation hooks documentation.

Upvotes: 4

Related Questions