Loopback relation - node.js

How to do the relation to match with an array of data in loopback
For e.g
My Models
// Regions model
{
"name": "regions",
"base": "PersistedModel",
"idInjection": true,
"options": {
"validateUpsert": true
},
"properties": {
"title": {
"type": "string",
"required": true
},
"images": {
"type": [
{
"target_id": {
"type": "string"
}
}
]
},
},
"validations": [],
"relations": {},
"acls": [],
"methods": {}
}
// Images model
{
"name": "images",
"base": "PersistedModel",
"idInjection": true,
"options": {
"validateUpsert": true
},
"properties": {
"name": {
"type": "string",
"required": true
},
"url": {
"type": "string",
"required": true
}
},
"validations": [],
"relations": { },
"acls": [],
"methods": {}
}
Expected output:
[
{
"title": "Region 1",
"field_images": [{
"name": "Image 2",
"url": "/media/image-1600x650.jpg",
},{
"name": "Image 1",
"url": "/media/image-1600x650.jpg",
}]
} ]

Assuming that the relationship is HasMany
{
"name": "regions",
"base": "PersistedModel",
...
"relations": {
"images": {
"type": "hasMany",
"model": "images",
"foreignKey": "title", //region title
}
}
...
}
A relationship is defined between two models. So, I highly doubt you would get the images inside an array (if you want to define a relationship between them).
But on loopback you can use separate APIs to retrieve the field_images instead of getting it as an array.
For example - you could retrieve the images like this
region.images([filter],
function(err, images) {
...
});

Related

loopback model json array of objects strict filter

I'm using strongloop loopback v3 REST API with mongoDB as datasource. My model order.json is
{
"name": "order",
"base": "PersistedModel",
"strict": true,
"idInjection": true,
"options": {
"validateUpsert": true
},
"properties": {
"orderNo": {
"type": "string"
},
"lines": {
"type": [
{
"type": {
"description": "string",
"quantity": "number"
}
}
]
}
},
"validations": [],
"relations": {},
"acls": [],
"methods": {}
}
I set "strict": true so that the model accepts only predefined properties. But this does not work for properties in the array lines.
I.E. if you post this object to the API you get an ValidationError (Code 422) as expected:
{
"orderNo": "xyz",
"someOtherProp": "hello",
"lines": [
{
"description": "abc",
"quantity": 5
}
]
}
But if you post this JSON object loopback saves the object to mongoDB
{
"orderNo": "xyz",
"lines": [
{
"description": "abc",
"quantity": 5,
"someOtherProp": "hello"
}
]
}
My question is about if there are any flags to be set in the model JSON to validate an array of objects? Or do I have to validate the nested documents by my own via the order.js model extension file?
define the lines as another model and make it relation with type embedsMany in order model.
lines model
{
"name": "line",
"base": "Model",
"strict": true,
"idInjection": true,
"properties": {
"description": {
"type": "string"
},
"quantity":{
"type":"number"
}
}
}
order model
{
"name": "order",
"base": "PersistedModel",
"strict": true,
"idInjection": true,
"options": {
"validateUpsert": true
},
"properties": {
"orderNo": {
"type": "string"
}
},
"validations": [],
"relations": {
"lines":{
"type": "embedsMany",
"model": "line",
"property": "lines"
}
},
"acls": [],
"methods": {}
}
this way loopback will validate line model

Loopback join/include two collections

I would like to include my product_product model inside product_template.
1 - Each product template has its own product_product variations "HasMany" .
2 - product_product has only one template "BelongsTo" product_template
3- product_template should be filled with only related product_product variations.
4- The two models are saved seprately, so when I call for find() function I would like to get a product_template model filled with the product_product related to it (Could be more than one)
Get product template function :
Producttemplate.find({
include: {
relation: 'variations',
scope: {
fields: ['sku', 'name', 'price', 'regular_price', 'weight', 'description', 'stock_quantity'],
},
},
})
product_product Model :
This model should be included in the product_template
{
"name": "product_product",
"base": "PersistedModel",
"strict": true,
"options": {
"validateUpsert": true
},
"properties": {
"_id_Odoo": {
"type": "number"
},
"sku": {
"type": "string",
"id": true,
"required": true,
"description": "Yes it's SKU"
},
#fields
},
"validations": [],
"relations": {
"product": {
"type": "belongsTo",
"model": "product_template",
"foreignKey": "_id_Odoo"
}
},
"acls": [],
"methods": {}
}
product_template Model :
This model should include the product_product
{
"name": "product_template",
"base": "PersistedModel",
"strict": true,
"options": {
"validateUpsert": true
},
"properties": {
"_id_Odoo": {
"type": [
"number"
]
}
"sku": {
"type": "string",
"id": true,
"required": true,
"description": "Yes it's SKU"
},
"name": {
"type": "string"
}
},
"scope": {
"include": "variations"
},
"hidden": ["_id_Odoo"],
"validations": [],
"relations": {
"variations": {
"type": "hasMany",
"model": "product_product",
"foreignKey": "_id_Odoo"
}
},
"acls": [],
"methods": {}
}
Result :
This the result of get product template above :
{ sku: 'AHWLI05942-FUSCHIA', variations: List [] },
{ sku: 'AHWLI05943-BLACK', variations: List [] },
{ sku: 'AHWLI05943-BURGUNDY', variations: List [] },
{ sku: 'AHWLI05944-BLACK', variations: List [] },
{ sku: 'AHWLI05944-MARRON', variations: List [] },
{ sku: 'AHWLI05945-BLUE', variations: List [] }
When I point into variations i get a function and into variations.list i get undefined any ideas how to get exact structure ?
example code part of my model "TeamRole" which belongsTo "Team" and User" in model level.
teamRole.json
"validations": [],
"relations": {
"team": {
"type": "belongsTo",
"model": "Team",
"foreignKey": ""
},
"user": {
"type": "belongsTo",
"model": "User",
"foreignKey": ""
}
}
Example search query for team role,
query.js
app.models.TeamRole.find({
where: {
userId: user.id
},
include: {
relation: 'team'
}
},function(err,teams){
console.log("teams will have all the include teams[] with team role ")
});
Hope using above example will help you.
sorry for late response, it was just misunderstanding of the relation and structure, i made a function that verifies if the product model exists in the template if yes, i push the template id in the product model and it worked fine.
product_product Model : I deleted the relation in the model below because it's useless, so i removed id property in sku and removed _id_Odoo field, then i added id field and parent_template field that contains the template model id.
{
"name": "product_product",
"base": "PersistedModel",
"strict": true,
"options": {
"validateUpsert": true
},
"properties": {
"id": {
"type": "number"
"id": true
}
"parent_template": {
"type": "number"
},
"sku": {
"type": "string",
"required": true,
"description": "Yes it's SKU"
},
#fields
}
product_template Model : I removed the _id_odoo and id property in sku and created an id for this model and in relation i made parent_template as foreignkey
{
"name": "product_template",
"base": "PersistedModel",
"strict": true,
"options": {
"validateUpsert": true
},
"properties": {
"id": {
"type": "number",
"id" : true
}
"sku": {
"type": "string",
"required": true,
"description": "Yes it's SKU"
},
"name": {
"type": "string"
}
},
"scope": {
"include": "variations"
},
##########
"relations": {
"variations": {
"type": "hasMany",
"model": "product_product",
"foreignKey": "parent_template"
}
},
#############
}

StrongLoop REST API "hasManyThrough" include filter always returns empty

Premise
Pretty short and simple. In my testing/learning environment for StrongLoop, I have set up two models: CoffeeShop and Person. Persons can have many "employers", and CoffeeShops can have many "employees". This relationship is maintained by a "hasMany"/"through" type relationship on both the CofeeShop and Person models.
Problem
When querying either model through the REST API, an include filter always returns an empty array for the associated relation, even if relations exist. In other words, the API call
http://localhost:3000/api/CoffeeShops/67/employees
works as expected, but
GET: http://localhost:3000/api/CoffeeShops/67/?filter={"include":["employees"]}
Does not.
Could anyone help me figure out why this is? I've attached pictures and the .json model definitions files as well.
// /common/models/coffee-shop.json
{
"name": "CoffeeShop",
"base": "PersistedModel",
"idInjection": true,
"options": {
"validateUpsert": true
},
"properties": {
"name": {
"type": "string",
"required": true
},
"city": {
"type": "string",
"required": true
},
"numberEmployees": {
"type": "number"
},
"ownerId": {
"type": "number"
},
"isSmallBusiness": {
"type": "boolean"
}
},
"validations": [],
"relations": {
"owner": {
"type": "belongsTo",
"model": "Person",
"foreignKey": ""
},
"employees": {
"type": "hasMany",
"model": "Person",
"foreignKey": "employerId",
"through": "CoffeeShopPersonEmployeeEmployer"
}
},
"acls": [],
"methods": {}
}
// /omon/models/person.json
{
"name": "Person",
"plural": "Persons",
"base": "PersistedModel",
"idInjection": true,
"options": {
"validateUpsert": true
},
"properties": {
"name": {
"type": "string",
"required": true
},
"age": {
"type": "number"
}
},
"validations": [],
"relations": {
"shops": {
"type": "hasMany",
"model": "CoffeeShop",
"foreignKey": "ownerId"
},
"employers": {
"type": "hasMany",
"model": "CoffeeShop",
"foreignKey": "employeeId",
"through": "CoffeeShopPersonEmployeeEmployer"
}
},
"acls": [],
"methods": {}
}
// /common/models/coffee-shop-person-employee-employer.json
{
"name": "CoffeeShopPersonEmployeeEmployer",
"base": "PersistedModel",
"idInjection": true,
"options": {
"validateUpsert": true
},
"properties": {},
"validations": [],
"relations": {
"person": {
"type": "belongsTo",
"model": "Person",
"foreignKey": "employeeId"
},
"coffeeShop": {
"type": "belongsTo",
"model": "CoffeeShop",
"foreignKey": "employerId"
}
},
"acls": [],
"methods": {}
}
Images of REST requests
in your CoffeeShopPersonEmployeeEmployer Model:
add foreign keys properties:
"properties": {
"CoffeeShopId": {
"type": "number",
"required": true
},
"PersonId": {
"type": "number",
"required": true
}
}
and ajust the relations :
"relations": {
"person": {
"type": "belongsTo",
"model": "Person",
"foreignKey": "PersonId"
},
"coffeeShop": {
"type": "belongsTo",
"model": "CoffeeShop",
"foreignKey": "CoffeeShopId"
}
}

Model Relation in Loopback framework

I want to establish a relation between two models, following the json files:
{
"name": "Surveyor",
"plural": "surveyors",
"base": "PersistedModel",
"strict": true,
"idInjection": true,
"options": {
"validateUpsert": true
},
"mongodb": {
"collection": "surveyors"
},
"settings": {
"mongodb": {
"allowExtendedOperators": true
}
},
"properties": {
"name": {
"type": "string",
"required": true
},
"surname": {
"type": "string",
"required": true
},
"dateOfBirth": {
"type": "date"
},
"birthPlace": {
"type": "string"
},
"provinceOfBirth": {
"type": "string"
},
"gender": {
"type": "string"
},
"registrationNumber": {
"type": "string",
"required": true,
"unique": true
}
},
"validations": [],
"relations": {}
},
"acls": [],
"methods": {}
}
{
"name": "Dossier",
"plural": "dossiers",
"base": "PersistedModel",
"strict": true,
"idInjection": true,
"options": {
"validateUpsert": true
},
"mongodb": {
"collection": "dossiers"
},
"settings": {
"mongodb": {
"allowExtendedOperators": true
}
},
"properties": {
"delCode": {
"type": "string",
"required": true
},
"client": {
"name": {
"type": "string",
"required": true
},
"surname": {
"type": "string",
"required": true
},
"taxCode": {
"type": "string"
}
},
"surveyor": {
"type": "string"
},
"examination": {
"type": "object"
},
"appointment": {
"type": "date"
},
"status": {
"type": "string",
"required": true
},
"notes": {
"type": "string"
}
},
"validations": [],
"relations": {},
"acls": [],
"methods": {}
}
One dossier can have one surveyor, as key I want to use the property surveyor in the Dossier Model, corresponding to the property registrationNumber in the Surveyor Model.
I want to query the dossier Model and obtain the surveyor data in the dossier doc:
[GET] /api/dossiers
or with a filter:
[GET] /api/dossiers?filter={"include":"surveyor"}
if it is possible I want to configure the relation in the json file, not in the code.
You can use the relation generator to create that for you. In your case you're going to need to create a belongsTO relation from Dossier to Surveyor. If you want to query the other way around (dossiers from a surveyor) you're going to need to create a hasMany relation from Surveyor to Dossier.
In short, for what you've asked, you're going to end up with something like this:
In Dossier model:
...
"relations": {
"surveyor": {
"type": "belongsTo",
"model": "Surveyor",
"foreignKey": "surveyor",
"primaryKey": "registrationNumber"
}
}
...

Add the current user before store a model strongloop

I recently start with Strongloop framework,
I made a simple model
{
"name": "income",
"plural": "incomes",
"base": "PersistedModel",
"idInjection": true,
"properties": {
"description": {
"type": "string",
"required": true
},
"amount": {
"type": "number",
"required": true
},
"when": {
"type": "date",
"required": true
}
},
"validations": [],
"relations": {
"user": {
"type": "belongsTo",
"model": "User",
"foreignKey": ""
}
},
"acls": [],
"methods": []
}
I want make a relation with current session user and the income record. but I can't find a example for that.
You can use the current context, there is a code example at the bottom of the link, but you have to expand it:
Link

Resources