user798719
user798719

Reputation: 9869

Strongloop: how to fetch a related model using code (not REST API)

Having trouble getting a related model on a User object. Users have a to-many relation with Customers.

Can I not just say User.customers to grab the customers associated with a User?

I have tried

User.find({include:'customers'}, function(err, user) {

   //now what?

  //user.customers does not work; there is no Customer array returned.



});

Happy to look in the docs for this but I can't find where this is written.

Thank you

Upvotes: 1

Views: 283

Answers (1)

Cameron
Cameron

Reputation: 876

In the loopback examples they often create a "user" model as an extension of loopbacks "User" model.

Note the lower case u.

I had trouble accessing the model when using "User" not "user"

user.json

{
 "name": "user",
 "base": "User",
 "idInjection": true,
 "emailVerificationRequired": false,
 "properties": {
 "createdAt": {
   "type": "date"
 },
 "updatedAt": {
  "type": "date"
 },
 .......

user.js

module.exports = function(user) {


user.observe('before save', function(ctx, next){
  if (ctx.instance) {
  //If created at is defined
  if(ctx.instance.createdAt){
    ctx.instance.updatedAt = new Date();
  }
  else{
    ctx.instance.createdAt = ctx.instance.updatedAt = new Date();
  }
} else {
  ctx.data.updatedAt = new Date();
}
next();
})`

Upvotes: 2

Related Questions