Ozitiho Ozitiho - 1 year ago 64
Node.js Question

How to include the 'many' part of a relation from the 'one of many' model?

I'm trying to get a product, including the category that it is a part of. A category of course has many products and a product is a part of one category. I do this like this.

Product.find({include: 'Categories'})

When I try to execute this query, I get an error. 'Relation "Categories" is not defined for Product model'.

I've defined this relation as according to the loopback docs found here: https://docs.strongloop.com/display/public/LB/HasMany+relations. As one category has many products. That looks as follows:


"relations": {
"products": {
"type": "hasMany",
"model": "Product",
"foreignKey": "categoryId"

Nothing is defined in products.json. I've checked the plurals of course, but they all check out.

When I try to get all products for all categories, it works without a problem. I'm pretty sure this is intended. But how am I supposed to do this the other way around? I already tried to define a relation in Product as hasOne, documented here: https://docs.strongloop.com/display/public/LB/HasOne+relations. But this requires a foreign key in the other object so that's obviously only meant for a 1-to-1 relation. Other than that I'm kind of stumped... Any ideas?

Answer Source

When you are including it from product side, you have to create that relation in product.json

As you mentioned, a product only belongs to one category - that means relation name should be category.

Think of it as something like, loopback will call a function Product.category

Add following snippet in product.json

"relations": {
  "category": {
    "type": "belongsTo",
    "model": "Category",
    "foreignKey": "categoryId"

Now try -

Product.find({include: 'category'})

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download