EmberJS - Multiple hasMany relationship on same attribute - ember.js

I have below json and I want to add multiple has many relationship.
{
"Id": "2311",
"package": [
{
"0": "233123"
},
{
"1": "1987797"
}
]
}
I want something like this in my model.
package : hasMany('package'),
package : hasMany('name'),
How can I use the hasMany relationship on same attribute for 2 models ?

I'm not sure I understand your question.
When you define hasMany relationship, for example, a client hasMany packages, you get the following representation in your database:
Client 1 { // Client model hasMany relationship to Package model
name: "client1"
id: "1234"
}
Package 1 {
name: "package1"
id: "233123"
client: "1234" // this package belongs to client 1
}
Package 2 {
name: "package2"
id: "1987797"
client: "1234" // this package also belongs to client 1
}
Are you saying you want your Client model to hold 2 hasMany relationships, one for the Package name and one for the Package ID?
Please provide a bit more detail and I'll help you answer the question.

Related

How to create register with relation model embeded?

I'm using Loopback 3 to create my application, with Postgres.
I've created a many-to-many usign hasManyThrough relation like this:
Product has many Composition
Ingredient has many Composition
Product has many Ingredient
Composition belongs to Product
Composition belongs to Ingredient
How can I create/edit a Product with a array of Ingredient's id, like:
POST /products
{
name: "Potato Chips",
ingredients: [ 5, 7, 3, 20 ]
}
And how can I get Product with list of Ingredients embeded?
GET /products/1
{
id: 1,
name: "Potato Chpis",
ingredients: [
{ name: "Potato" },
{ name: "Vegetal Oil" }
...
]
}
1/ To create a Product with many Ingredients, I suggest to make a custom remote that takes your product in the body along with the ingredients, and make a loop over the ingredients to link them to your product one by one, using the add method (assuming that Product has many Ingredients through Composition):
Product.ingredients.add(ingredientData, callback);
2/ To get a Product with its embedded list of Ingredients, you need to include the relation property to your GET route (example given in reactjs):
const response = await Axios.get(`/api/products/${productId}`, {
params: {
filter: {
include: [
{ relation: 'ingredients' },
],
},
},
});

Loopback 4 and Mongodb : All model's id are null on response

It is the first time that I use this version (4) for development and I have a problem with loopback and mongodb indexing.
Of the two ids that are inside the db loopback it does not collect any.
It's a problem of the API or DB?
Model [Loopback]
import { Entity, model, property } from '#loopback/repository';
#model()
export class Ad extends Entity {
#property({
type: 'number',
id: true,
required: true,
})
id: number;
<...>
constructor(data?: Partial<Ad>) {
super(data);
}
}
Data on Mongo:
{
"_id": {
"$oid": "5c0e9c7730146d2448746834"
},
"id": 110722,
"creation_date": 1492075600000,
"update_date": 1492075921000,
...
}
Response on loopback GET /ads
[{
"id": null,
"creation_date": 1492075600000,
"update_date": 1492075921000,
...
},...]
Hello from the LoopBack team :)
I don't see any obvious problem in the code snippets you posted. What happens when you change id's type from number to string? Will it fix the problem?
Most likely, you have found a bug in LoopBack 4. Please report it via GitHub: https://github.com/strongloop/loopback-next/issues
I fixed the same issue by changing the id=String. Mongodb id contains both string and number. So, if you change the type of id=string (Model) the issue will be fixed.

Can Ember-Data handle two models from one JSON payload?

I have JSON coming from the server which looks like:
data: {
user: {
address: {
id: "id",
city: "city",
street: "street",
.......
}
name: "name",
......
}
authentication-token: {
token: "token",
id: "id"
}
}
The idea is to store this two models (user, authentication-token) in ember store under the same names. When I gat the above mentioned response from a server, model user is saved successfully, but model authentication-token does not get saved to the store at all. When I log the data (in the adapter) before the data is passed to serializer I see that JSON has a structure which Ember-Data expects. I don't know whether the problem is that Ember-Data cannot handle two models in success at one time, and then save it to the corresponding models, or something else. Ideas?
Now it all makes sense to me. Of course, this was the problem in your last question. Anyway, ember-data's RESTAdapter can't handle this. If you're requesting a singular resource user it expects at most this user as a singular answer. Any other resource that may be "side-loaded" has to be an array. The requested singular user can either be a record under the user key or the first entry in an array unter the users key. Everything else (except meta data) has to be plural.
In case you're requesting a plural resource users, the main response must be under the users key, any sideloaded users that aren't part of the response prfixed with _ under the _users key.
For your example all this means that your json must be formatted like this:
data: {
user: {
address: {
id: "id",
city: "city",
street: "street",
.......
}
name: "name",
......
}
authentication-tokens: [{
token: "token",
id: "id"
}]
}
If you can't change your server, you'd have to configure the RESTAdapter to normalize the JSON data through normalize of the Serializer.

Ember: dumplicated records are created in store after model save action

I have two models in my ember app:
App.Order = DS.Model.extend
orderItems: DS.hasMany('orderItem')
App.OrderItem = DS.Model.extend
order: DS.belongsTo('order')
I tried to save orderItem, bellow is the payload I got after save invoking.
{
orderItem:{
id:1
order:"1"
},
orders:[
{
id:"1",
orderItems:["1","2","3"]
}
],
orderItems:[
{
id:"1",
order:"1"
},
{
id:"2",
order:"1"
},
{
id:"3",
order:"1"
}
]
}
Then, I found 2 duplicated orderItems records in ember store with same id(id=1).
I don't know how does ember push payload after model saving.
error will be shown if removing orderItem(id=1) from orderItems hash.
Who can tell me what's the root cause?

Ember data sideloaded models ignored

I'm new to Ember, and am having a problem I'm not seeing duplicated anywhere else so I'm sure I'm doing something silly. I have these models:
App.User = DS.Model.extend({
username: DS.attr("string"),
userId: DS.attr("number"),
modules: DS.hasMany("App.Module")
});
App.Module = DS.Model.extend({
moduleId: DS.attr("number"),
name: DS.attr("string")
});
Note that my Module model is simply a container that a User can have a few of, and many users might share the same modules - they're actually represented by an Enum on the server. As such, the backend does not have a mapping of Module > Users, so I've left the DS.ownedBy or DS.hasMany out of App.Module. I have, however, tried my test with a "users: DS.hasMany('App.User')" in there as well, with the same result. If it turns out to be necessary, I could maintain such a mapping, but I have no other reason for doing so right now, so it would be a bit unfortunate to be forced to add such a table to my database.
I'm using Ember.Auth for authentication, and when my app loads up and I log in, the server requests (as expected):
users/nathan?authToken=<token>
The result is also as I think it should be, according to the ember data docs:
{
"user": {
"username": "nathan",
"user_id": 1,
"module_ids": [1,2]
},
"modules": [
{"module_id": 1, "name": "Account Settings"},
{"module_id": 2, "name": "Manage Websites"}
]
}
I'm then testing in the Chrome console with:
App.Auth.get("user").get("modules");
or
App.User.find("nathan").get("modules");
and in both cases, Ember makes a request to my server to get the data for Modules 1 and 2. If I repeat the same request, it doesn't go back to the server again, so it is storing the result properly that time, it's simply the sideload that it's ignoring.
I'm using ember-1.0.0-rc4 with ember-data-0.13.
In your sideload response, module_id should be id.
(or you can configure ember-data to use module_id, but formatting the server response should be the easier way?)
--- edit for explanation ---
I'm not sure the original REST call is "working perfectly". Without the id. ember-data does see the two modules that your originally sideloaded, but it sees no id, so it does not know that they are modules 1 and 2 respectively. By default (changeable), ember-data expects the id to be called id; your module_id (and user_id) are just treated as regular properties.
On your next API call (to /modules?ids[]=1&ids[]=2 presumably), ember-data silently assumes that, since your requested two modules, and two modules came back, they should be the two that you requested. Try sending back this
{
"modules": [
{"module_id": 3, "name": "Foo module"},
{"module_id": 4, "name": "Bar module"}
]
}
for the request /modules?ids[]=1&ids[]=2, you will still get your "successful" observation.
Try App.Module.find(1).get('name') with the module_id-response - you will get undefined; now try it with the id-response, and you will get Account settings as expected.
Have you configured your RestAdapter to sideload modules?
Like this:
DS.RESTAdapter.configure('App.Module', {
sideloadsAs: 'modules'
});