Create with associated instances - Sequelize - javascript

Using sequelize ORM you can create with association in one swoop:
Product.create({
id: 1,
title: 'Chair',
Tags: [
{ name: 'Alpha'},
{ name: 'Beta'}
]
}, {
include: [ Tag ]
})
My question is: How would I go about this when I have to work with an array of an arbitrary number of elements (here Tags) passed along?

The question is not clear. But if you mean what if you have many attributs like Tags which are associations, maybe what you are looking for is:
include: [{
all: true
}]
or
include: [{
all: true,
include: [{
all: true
}]
}]
For nested elements.

Related

Edit multiple objects in array using mongoose (MongoDB)

So I tried several ways, but I can't, I can modify several objects with the same key but I can't modify any with different keys, if anyone can help me is quite a complex problem
{
id: 123,
"infos": [
{ name: 'Joe', value: 'Disabled', id: 0 },
{ name: 'Adam', value: 'Enabled', id: 0 }
]
};
In my database I have a collection with an array and several objects inside which gives this.
I want to modify these objects, filter by their name and modify the value.
To give you a better example, my site returns me an object with the new data, and I want to modify the database object with the new object, without clearing the array, the name key never changes.
const object = [
{ name: 'Joe', value: 'Hey', id: 1 },
{ name: 'Adam', value: 'None', id: 1 }
];
for(const obj in object) {
Schema.findOneAndUpdate({ id: 123 }, {
$set: {
[`infos.${obj}.value`]: "Test"
}
})
}
This code works but it is not optimized, it makes several requests, I would like to do everything in one request, and also it doesn't update the id, only the value.
If anyone can help me that would be great, I've looked everywhere and can't find anything
My schema structure
new Schema({
id: { "type": String, "required": true, "unique": true },
infos: []
})
I use the $addToSet method to insert objects into the infos array
Try This :
db.collection.update({
id: 123,
},
{
$set: {
"infos.$[x].value": "Value",
"infos.$[x].name": "User"
}
},
{
arrayFilters: [
{
"x.id": {
$in: [
1
]
}
},
],
multi: true
})
The all positional $[] operator acts as a placeholder for all elements in the array field.
In $in you can use dynamic array of id.
Ex :
const ids = [1,2,..n]
db.collection.update(
//Same code as it is...
{
arrayFilters: [
{
"x.id": {
$in: ids
}
},
],
multi: true
})
MongoPlayGround Link : https://mongoplayground.net/p/Tuz831lkPqk
Maybe you look for something like this:
db.collection.update({},
{
$set: {
"infos.$[x].value": "test1",
"infos.$[x].id": 10,
"infos.$[y].value": "test2",
"infos.$[y].id": 20
}
},
{
arrayFilters: [
{
"x.name": "Adam"
},
{
"y.name": "Joe"
}
],
multi: true
})
Explained:
You define arrayFilters for all names in objects you have and update the values & id in all documents ...
playground

how to return values from joined tables in sequelize at the same level as master table

I am trying to find a way how to put all joined tables at the same level as my master table... so far it only results in the nested values in my final object ..
Here is what I have
Orders.findAll({
include: [
{model: Products, attributes: ['product_name']}
],
attributes: ['id_order', 'dtime_order', 'amount']
})
what I am getting is:
[
{
id_order: 1,
dtime_order: '2021-05-24T22:00:00.000Z',
amount: 20,
products: {
product_name: 'Picture'
}
}
]
but what I wanna get is:
[
{
id_order: 1,
dtime_order: '2021-05-24T22:00:00.000Z',
amount: 20,
product_name: 'Picture'
}
]
I tried this How to return result from include model in same level of main model in Sequelize? but unfortunately when I did:
Orders.findAll({
include: [
{model: Products, attributes: []}
],
attributes: ['id_order', 'dtime_order', 'amount', ['products.product_name', 'product_name']]
})
doesn't work for me saying
column "products.product_name" does not exist
There might be a hacky way to modify the object before sending it back in the response .. but I would rather do it within Sequelize ..
any idea is very welcome... thank you guys!
EDIT: adding the generated SQL
Executing (default): SELECT "orders"."id_order", "orders"."dtime_order", "orders"."amount", "products.product_name", FROM "orders" AS "orders" LEFT OUTER JOIN "products" AS "products" ON "orders"."id_order" = "products"."ir_order";
error: Get dashboard data error: column "products.product_name" does not exist
SOLUTION:
I had to use an alias in my association
Orders.hasOne(Products, {as: 'products', ....})
And then use that EXACTLY SAME alias in my include and referencing
include: [{model: Products, attributes: [], as: 'products'}]
And
attributes: [ ... , [Sequelize.col('products.product_name', 'product_name')]
without the raw: true works like a charm :) Thank you #Emma !!!
Please use Sequelize.col to wrap the nested column so that Sequelize can properly alias the column.
Orders.findAll({
include: [
{model: Products, attributes: []}
],
attributes: ['id_order', 'dtime_order', 'amount', [Sequelize.col('products.product_name'), 'product_name']],
raw: true
})

Normalizr normalize nested data

I have a nested data which looks like this:
{
components: [
guid: "cms-container/c154c79596b3af6326966b0c994e2a934",
regions: [{
guid :"r1c154c79596b3af6326966b0c994e2a934",
components: [{
guid: "cms-markupfile/owg-header.html" },
{ guid: "cms-navmenu/n1503636374400" },
{ guid: "cms-container/c50c451ba72e4b4edab979cf477129215",
regions: [{
guid: "r1c50c451ba72e4b4edab979cf477129215",
components: [{
guid:"cms-serie/serieDetailRenderer"
}]
}]
},
]
}]
]
}
As you can see this is a nested structure with arbitrary nesting.
That is, in the components array there can be also an array of region in which, in turn, there can be another components array.
I'm trying to bring this structure to a flat form with normalizr but so far without result. I would be grateful for the help in solving this problem.
I would try something as simple as that :
import { schema } from 'normalizr'
const schemas = {
component: new schema.Entity('components'),
region: new schema.Entity('regions')
}
schemas.component.define({
regions: [schemas.region]
})
schemas.region.define({
components: [schemas.component]
})
I'm afraid of circular references, but it's worth trying.
If it's not working can you supply what you've done so far ?
Old question, but the answer might be useful to someone.
If I understand correctly, each component contains unique identifier (guid) and possibly an array of regions, while each region contains unique identifier (guid) and possibly an array of components. If that is the case, you are missing a couple of {} inside the outermost components array. Instead of
{
components: [
you should write
{
components: [{
And at the end, instead of
]
}
you should write
}]
}
Now, suppose my understanding of your data is correct, and suppose you make correction as suggested, your normalizr schema should look as folowing:
import { schema, normalize } from 'normalizr'
const regionSchema = new schema.Entity(
'regions',
{ components: [ componentSchema ] },
{ idAttribute: 'guid' }
)
const componentSchema = new schema.Entity(
'components',
{ regions: [ regionSchema ] },
{ idAttribute: 'guid' }
)
and you should normalize your data like this
let data = [{
guid: "cms-container/c154c79596b3af6326966b0c994e2a934",
regions: [{
guid :"r1c154c79596b3af6326966b0c994e2a934",
components: [{
guid: "cms-markupfile/owg-header.html" },
{ guid: "cms-navmenu/n1503636374400" },
{ guid: "cms-container/c50c451ba72e4b4edab979cf477129215",
regions: [{
guid: "r1c50c451ba72e4b4edab979cf477129215",
components: [{
guid:"cms-serie/serieDetailRenderer"
}]
}]
},
]
}]
}]
let normalizedData = normalize(data, [componentSchema])

Iterate through module in AngularJS

I'm facing this problem in AngularJS; I'm using the Drag & Drop from Github and I've using the Nested example, but I want to implement the identity types as well, but I can't iterate through the array it gives me cause I really don't know how.
list: [
0: {
type: container
allowedTypes: [ ... ]
id: Desayuno
columns: [ ... ]
}
1: {
type: container
allowedTypes: [ ... ]
id: ColaciĆ³n
columns: [ ... ]
}
I've just need the allowedTypes values... I've tried this:
<ul dnd-list="list"
dnd-allowed-types="(key, allowedTypes) in list">
<h3>{{list.id}}</h3>
but it gives me error .-.
Reading the docs of this lib, there are something wrong in your list. First, it should be an object. Secondely, the key should be a string(not sure, but you can try). Finally, the objets should be nested in the array. So it should be something like this:
list: {
'0': [{
type: container,
allowedTypes: [ ... ],
id: Desayuno,
columns: [ ... ]
}],
'1': [{
type: container,
allowedTypes: [ ... ],
id: ColaciĆ³n,
columns: [ ... ]
}]
}
Also, you should modify your html to get the right element in the list.

Best way to design a model for the store for a array?

I need to import the following into a store but I am confused about the correct model or models I need to create.
here is an example of the JSON that is returned from my server. Basically its an array with 2 items, with an array in each. The field names are different in each.
I suspect I need to have more than one model and have a relationship but I am unsure where to start. Any ideas? Thanks
[
firstItems: [
{
name : "ProductA",
key: "XYXZ",
closed: true
},
{
name : "ProductB",
key: "AAA",
closed: false
}
],
secondItems : [
{
desc : "test2",
misc: "3333",
},
{
desc : "test1",
misc: "123"
}
]
]
What you have is not JSON, your opening and ending [] can become JSON by changing them to {} and then using the following models
Then you can model it as
// Abbreviated definitions of Models, it has changed starting at Ext 5
Ext.define('FirstItem', fields: ['name', 'key', 'closed'])
Ext.define('SecondItem', fields: ['desc', 'misc'])
Ext.define('TopLevel', {
hasMany: [
{model: 'FirstItem', name: 'firstItems'},
{model: 'SecondItem', name: 'secondItems'}
]
})
Use the reader for store's proxy, it will create appropriate model on load.
If you need to load already loaded json into the store use loadRawData but reader you will need in any case.

Categories

Resources