I have two models Question and Answer. A Question has many Answers, and an Answer belongs to a Question.
Then in Loopback provides a reference to an Answer. What I can't figure out is how do I then get a reference to the Question that the Answer belongs to!?
module.exports = function(Answer) {
console.log(ctx.instance.question)
console.log(ctx.instance.question.points) // undefined
};
I can get what looks like a reference to the object ... but I don't know how to reference any properties on that object!?
How do I reference a model that belongsto another model?
Question and Answer provided below for reference.
{
"name": "Question",
"plural": "Questions",
"base": "PersistedModel",
"idInjection": true,
"options": {
"validateUpsert": true
},
"properties": {
"text": {
"type": "string",
"required": true
},
"points": {
"type": "number",
"required": true
}
},
"validations": [],
"relations": {
"answers": {
"type": "hasMany",
"model": "Answer",
"foreignKey": ""
},
"approval": {
"type": "hasOne",
"model": "Approval",
"foreignKey": ""
},
"student": {
"type": "belongsTo",
"model": "Student",
"foreignKey": ""
}
},
"acls": [],
"methods": {}
}
{
"name": "Answer",
"plural": "Answers",
"base": "PersistedModel",
"idInjection": true,
"options": {
"validateUpsert": true
},
"properties": {
"text": {
"type": "string",
"required": true
}
},
"validations": [],
"relations": {
"question": {
"type": "belongsTo",
"model": "Question",
"foreignKey": ""
},
"student": {
"type": "belongsTo",
"model": "Student",
"foreignKey": ""
},
"approval": {
"type": "belongsTo",
"model": "Approval",
"foreignKey": ""
}
},
"acls": [],
"methods": {}
}
I'm guessing that the code you provided is from your common/model/answer.js
file based on what it looks like, but that file is executed during application set up. The context (ctx
in your sample) would not exist there. Context is only given during a remote hook or other such action. As such, I'll give you an answer based on a hook for finding an Answer
by its ID and then getting the related question. This code should go in your common/model/answer.js
file (inside the exported wrapper function):
Answer.afterRemote('findById', function(ctx, theAnswer, next) {
theAnswer.question(function(err, question) { // this is an async DB call
if (err) { return next(err); } // this would be bad...
console.log(question);
// You can then alter the question if necessary...
question.viewCount++
question.save(function(err) {
if (err) {
// an error here might be bad... maybe handle it better...
return next(err);
}
// if get here things are good, so call next() to move on.
next();
});
});
});
Note that if you wanted to do this during some other step in the request-response cycle it might be different. You would hit this remote hook any time a call to /api/Answers/[id]
is hit.
Seconde note: you can also get this data straight from the API if you just need it on the client:
.../api/Answers?filter={"include":"question"}
[Updated to show saving a question.]