how to get array of sequelize and mysql objects? - mysql

hello I have a nodejs project, I am using sequelize and mysql2 to access the database, in one of its routes I show an ejs view and I want to send a variable to it so that different products/cards are dynamically loaded from a form.
now when I use the findAll() method to call the different mysql records I try to bring an array of objects but it returns the loose objects so in the ejs view I cannot iterate with a foreach() for example
I execute this from a home route
i try this
products_dataBase.findAll()
.then(products => {
products.forEach(element => {
let result = []
result.push( element.dataValues)
res.render('home.ejs', { result });
console.log(result)
});
})
.catch(err => {
console.log(err)
})
[
{
id: 14,
title: 'asdasd',
price: 33434,
description: 'sdasd',
createdAt: 2022-11-08T02:06:12.000Z,
updatedAt: 2022-11-08T02:06:12.000Z
}
]
[
{
id: 15,
title: 'asodfsd',
price: 232,
description: 'asdasd',
createdAt: 2022-11-08T03:17:20.000Z,
updatedAt: 2022-11-08T03:17:20.000Z
}
]
[
{
id: 16,
title: 'ldfsksdf',
price: 343434,
description: 'efsddsff',
createdAt: 2022-11-08T03:17:44.000Z,
updatedAt: 2022-11-08T03:17:44.000Z
}
]

res.render must be executed only once per request, but you invoke it repeatedly, in a forEach loop. Try this:
products_dataBase.findAll()
.then(products => {
let result = [];
products.forEach(element => {
result.push(element.dataValues);
});
res.render('home.ejs', { result });
console.log(result);
})
.catch(err => {
console.log(err);
});

Related

pass values of json object in react native to another object

I used a fetch API to get data from backend server. I returned JSON object data from fetch function and I want to pass every single value in the object to another object.
function getvals() {
return fetch('http://*********/users/timetable')
.then(response => response.json())
.then((responseData) => {
console.log(responseData);
return responseData;
})
.catch(error => console.log(error))
}
the function getvals() is returning the object data, these data looks like this:
[{"title": "Math","day": "FRI", "end_time": 11, "start_time": 9,location: "Classroom 403",extra_descriptions: "Chen"}]
now I want every single value of the object data to be passed to this object:
const events_data = [
{
title: "Math",
startTime: genTimeBlock("WED", 9),
endTime: genTimeBlock("WED", 10),
location: "Classroom 403",
extra_descriptions: ["Kim", "Lee"],
},
{
title: "Mandarin",
startTime: genTimeBlock("TUE", 9),
endTime: genTimeBlock("TUE", 10),
location: "Language Center",
extra_descriptions: ["Chen"],
},
{
title: "Japanese",
startTime: genTimeBlock("FRI", 9),
endTime: genTimeBlock("FRI", 10),
location: "Language Center",
extra_descriptions: ["Nakamura"],
},
];
for example the value of day from getvals() function i want to pass it to be set in in startTime in events_data object
then within the the view the events_data will be passed to events props:
<SafeAreaView style={{ flex: 1, padding: 30 }}>
<View style={styles.container}>
<TimeTableView
scrollViewRef={this.scrollViewRef}
**events={// events.data will be passed here as object format //}**
pivotTime={8}
pivotDate={this.pivotDate}
numberOfDays={this.numOfDays}
onEventPress={getvals}
headerStyle={styles.headerStyle}
formatDateHeader="dddd"
locale="en"
/>
</View>
</SafeAreaView>
it may the way to do this is easy but im new with this approche and i couldn't find an easy way to do it.
You can map over the data and then add them to the array events_data.
The function addData pushes the data received from the fetch request in the desired format to the events_data.
function getvals() {
fetch("http://*********/users/timetable")
.then((response) => response.json())
.then((output) => {
addData(output, events_data);
})
.catch((error) => console.log(error));
}
function addData(data, data2) {
data.forEach(d) => {
data2.push({
title: d.title,
startTime: genTimeBlock(d.day, d.startTime),
endTime: genTimeBlock(d.day, d.endTime),
location: d.location,
extra_description: [d.extra_description],
});
});
}
Edit:
If you wanted to render the data then you can do it like this:
const RenderData = () => {
return (
<View>
{events_data &&
events_data.result.map((data) => {
return <Text>{data.title}</Text>;
})}
</View>
);
};

Realm JS react-native can't create table from a large JSON from API with to-many relationship

In my React-Native app, using Realm DB JS, I have these three classes: TableOfProducts, Product, BarCodeProducts.
The class TableOfProducts has a list of Products and the class Product has a list of BarcodeProducts.
I model them like these:
export default class TableOfProductsSchema {
static schema = {
name: 'TabelaOfProducts',
primaryKey: 'cdTabelaPreco',
properties: {
cdTabelaPreco: {type: 'int', indexed: true},
dsTabelaPreco: 'string',
product: 'Product[]',
//I already tried like: product: {type: 'list', objectType: 'Product'}
},
};
}
export default class ProductSchema {
static schema = {
name: 'Product',
primaryKey: 'tableProduct',
properties: {
tableProduct: {type: 'string', indexed: true},
cdTableOfProduct: 'int',
idProduct: 'int',
dsProduct: 'string',
barcodeproducts: 'ProdutoCodigosBarra[]',
//I already tried like: barcodeproducts: {type: 'list', objectType: 'BarCodeProducts'}
},
};
}
export default class BarCodeProductsSchema {
static schema = {
name: 'BarCodeProducts',
primaryKey: 'idProductNrItem',
properties: {
idProductNrItem: {type: 'string', indexed: true},
idProduct: 'int',
nrBarCode: 'int',
barCodeItem: 'string',
barCodeBox: 'string',
qtBox: 'double',
},
};
}
And I have this code to get the JSON and create the data in my Realm DB:
requestTableOfPoducts = async (httpClient) => {
let itens = null;
await httpClient
.get(apiConfig.url_table_products, {
timeout: 999000,
})
.then((response) => {
itens = response.data;
})
.catch((error) => console.log(error));
console.log(itens); //runs ok and show the large JSON in console so my API is receiving itens..
return new Promise((resolve) => {
if (itens) {
const databaseOptions = {allSchemas};
Realm.open(databaseOptions).then((realm) => {
realm.write(() => {
const resolveItens = itens.tableOfProducts.map(async (obj, k) => {
return realm.create('TableOfProducts', obj, true);
});
Promise.all(resolveItens).then(() => resolve(true));
});
});
} else {
resolve(true);
}
});
};
The big problem here is: If I receive a small JSON data from API like just one TableOfProducts with a small list of Product, just 2 products, and two barcodes each product in the table BarCodeProducts my code runs ok and realm save all records correctly (1 record for TableOfProducts, 2 records for Product and 4 records for BarCodeProducts) but if I receive a large JSON (5MB), lots of records like 4 TableOfProducts and almost 50000 Products with more 20000 BarCodeProducts, with the same structure, I receive the error in console:
WARN Possible Unhandled Promise Rejection (id: 0):
TypeError: undefined is not an object (evaluating 'itens.tableOfProducts.map')
I already tried to use ".. JSON.parse(itens) .." but I receive a message that my JSON it's already a JSON parsed.
Please, please, please.. Someone Can please help me ? What could be wrong ? There is another way ?

How to insert data to JSON file dynamically?

json file img
Note: I wanna insert data without write that into .json file. such as Angularfire2 database.
user = {
name: 'Arthur',
age: 21
};
const options = {Headers, responseType: 'json' as 'blob'};
this.httpService.put('assets/data/ex.json', this.user, options).subscribe(
data => {
console.log(data);
},
(err: HttpErrorResponse) => {
console.log (err.message);
}
);
You can directly access the object using dot operator
user = {
name: 'Arthur',
age: 21
};
const options = {Headers, responseType: 'json' as 'blob'};
this.httpService.put('assets/data/ex.json', this.user, options).subscribe(
data => {
console.log(data);
data.user.lastName = 'stackoverflow';
},
(err: HttpErrorResponse) => {
console.log (err.message);
}
);

React-Native render json from fetch

I have a fetch returning on ComponentDidMount(). Trying to get the response to render on the page.
I have set the state as follows:
this.state = {
loading: true,
file: null,
video: null,
marks: []
};
and my fetch:
componentDidMount() {
return fetch('http://10.0.2.2:8080/marks/createMark')
.then(response => response.json())
.then((data) => {
this.setState({
loading: false,
marks: data.mark
}, () => {
console.log(data.mark);
console.log(this.state.marks);
// const dataMap = data.mark.map((item) => {
// return {
// key: item.id,
// label: item.mark
// };
// });
});
})
.catch(err => console.log(err));
}
Now my render inside of the return:
const { marks } = this.state;
<FlatList
data={marks}
renderItem={({ item }) => <Text>{item.mark}</Text>}
keyExtractor={(item, index) => index}
/>
Do I have to map the data then try to render it??
OUTPUT OF console.log(this.state.marks):
{ _id: '5b61e47a55a0000aa980fab1', mark: 'ItHe', __v: 0 }
The mark is a pseudorandom string that can contain letters and numbers created on the backend
As this.state.marks is an object. First, you need to convert it to this form [{}]. You can do the following changes to make it work.
fetch('http://10.0.2.2:8080/marks/createMark')
.then(response => response.json())
.then((data) => {
let marks = [data.mark]; //Add this line
this.setState({
loading: false,
marks: marks // Change this line
}, () => {
....
Rest of your code
marks is an array but you're not sharing what each object in the array looks like. If it's an array of strings, you're good but if it's an object, you'll need to destructure it and pull out the string you're looking to render.
<Text>{item.mark.someKeyWhoseValueIsAString}</Text

Update record using sequelize(mysql) + nodejs

My table name: TIME
My table data fields:
start : 10.00am
stop: null
Now i want to update null as current date
exports.updateGroup = function (req, res) {
Time.update(req.body, {
stop: new Date(),
where: {
id: req.body.id
}
}).then(data => {
return res.status(200).send(data);
}).catch(Sequelize.ValidationError, err => {
return res.status(422).send(err.errors[0].message);
}).catch(err => {
return res.status(400).send(err.message);
});
};
Now its showing same as null after update
My req.body: { mainId: 1, start: '', stop: '' }
my Time model :
var Time = sequelize.define('time', {
start: Sequelize.DATE,
stop: Sequelize.DATE,
});
Firstly, you pass wrong id since there is not a req.body.id property based on body format you've posted.
Secondly, the update method gets two arguments as referenced at official sequelize documentation.
This should work:
Time.update({
start: req.body.start,
stop: req.body.stop
}, {
where: {
id: req.body.mainId
}
})