Sequelize raw queries TextRow and getting data out of it - mysql

Given this query here,
let output = [];
const sql = `select * from coredb.account LIMIT ${offset},${limit}`;
let data = await sequelize.query(sql, null, {raw: true, type: sequelize.QueryTypes.SELECT});
data.forEach((item) => {
console.log(item['id'], item.id); // <-- output says "undefined, undefined"
});
the data variable is indeed hydrated with the right row data when using console.log to inspect it.
But, when I try to access the individual properties, they only ever come back as undefined. This TextRow object that Sequelize seems to return the result in doesn't seem to want to let me access then explicit rows.
Just curious what i'm missing here, am I missing an option?

I agree, Sequalize raw queries are not intuitive. You don't need the null or raw: true flag. Something like this should work:
let data = await sequelize.query(sql, {type: sequelize.QueryTypes.SELECT});

When I tried this, "data" was an array of two objects, each being the query result. So, the properties can be accessed by using index [0].... e.g.
data[0].forEach((item) => {
console.log(item['id'], item.id); // <-- output says "undefined, undefined"
});
Not yet sure WHY this occurs!
EDIT - it's because .query() should have only two arguments. Changing the call to: sequelize.query(sql, {raw: true, type: sequelize.QueryTypes.SELECT}) resulted in data being a single array (as expected).

Finally I was able to find the solution for it.
You just need to make a new array and push data into it by finding bases on key name like this:
suppose we have data in students object:
let finalArray = new Array();
for (var k in students ) {
finalArray.push(students[k])
}
console.log(finalArray) // Normal JSON array object :)

m.sequelize.query(sql, {
model,
mapToModel: true
})
.then(model => res.status(200).send(model))
.catch(error => res.status(400).send(error.toString())
})

Related

Apparently no causes for the error "TypeError: Cannot read properties of undefined "

I have to show in the layout some data I take from a database. Here is the code I use to fetch the data:
const [array, setArray] = useState([])
const collectionRef = collection(db, "Collection")
const q = query(collectionRef, orderBy("Order", "desc"))
useEffect(() => {
auth.onAuthStateChanged(function (user) {
if (user) {
onSnapshot(q, (data) =>
setArray(data.docs.map((doc) => ({ ...doc.data(), id: doc.id })))
);
}
})
}, [auth]);
Below is the html
<div>
<h2>{array[0].Name}</h2>
</div>
What baffles me most is that the error does not always show up, sometimes everything works and sometimes it stops working without apparent causes. If I do console.log of the array sometimes it prints the data and everything works, sometimes it prints an empty array and does nothing.
I state that that array is never modified, it is loaded at the beginning of the code and the data is only read.
array is empty for the first render and for all the other renders until the data is returned. Try something like:
<div>
<h2>{array.length && array[0].Name}</h2>
</div>

How to delete all in json server

I am using this json server in my Angular app, to create, fetch, and delete posts.
In the following method, I delete a post with a specified id:
deleteConsumer(post: Post): Observable<Post> {
const url = `${this.apiUrl}/${post.id}`;
return this.httpClient.delete<Post>(url);
}
I looked at the .delete code and searched for something like a .deleteall but could not find it. Is there really no such method that would delete everything?
If there really isn't, then my attempt at doing it myself is not paying off, because what I have done is not working:
deleteConsumers(): Observable<Post> {
let i: number = 0;
this.httpClient.get<Post[]>(this.apiUrl).forEach(
() => {
++i;
const url = `${this.apiUrl}/${i}`;
return this.httpClient.delete<Post>(url);
}
);
}
Obviously, this is wrong in terms of return type, but I cannot figure out what to do... How can I modify the first method, so it would go through all the json objects in my db.json file; meaning iterate through all the existing posts and delete them all?
I did encounter this when using json-server with Vue.js and I realized that there was no special function to delete all at once. I had to work around it.
So, for example in your case, I would first map the posts array to get a new array with only the post ids:
const postsIdsArray = this.posts.map((post) => post.id)
Then, assuming you already have a function to delete one post given the id, I would then execute the function for each of the ids in the array:
postsIdsArray.forEach((id) => this.deletePost(id))
Just combine the two lines in one JavaScript function (in this case I used Vue.js):
deleteAllPosts(){
const postsIdsArray = this.posts.map((post) => post.id)
postsIdsArray.forEach((id) => this.deletePost(id))
}

How to retrieve a name from the data in response in vuejs

I have a issue that i want to get the name from the response of api.
Here is what i have, i have response like this:
capabilities: (55) ["x:list", "y:create", "z:retrieve"]
created_at: "2021-03-09T14:13:18.214999Z"
test: null
description: "test"
What i want to that to have only get the "x:list" from the above
Here is what i am doing is:
this.response.data.data
Please help
I do not know how you process the data, so I cannot give an exact answer. I guess it would be something like this
const { capabilities } = this.response.data
const xList = capabilities.find(item => item === "x:list")
console.log(xList)

Sails js: select records from mysql?

I am trying to select all records from table called fairCustomer where business_type_id equal array of value.
I am using sailsjs for server and mysql for DB, in frontend I am using nativescript with typescript.
and this is my code:
filterShopType(){
this.service.serviceName = 'fairCustomers';
this.service.Get({ populate:'country_id,business_type_id',where:{ business_type_id:{ in:this.business_ids_filter } }, limit:20 }).then((data: any) => {
this.fairCustomers.splice(0, this.fairCustomers.length);
this.fairCustomers.push(data);
this.Refresh('fairCustomers');
}).catch((err) => {
console.log('failed get fairCustomers from server ', err);
});
}
service refer to http.request(), where i am using it in another place in my code.
business_ids_filter is an array of ids.
When I run this code the I am getting this error:
"message": "Could not parse the provided where clause. Refer to the Sails documentation for up-to-date info on supported query language syntax:\n(http://sailsjs.com/documentation/concepts/models-and-orm/query-language)\nDetails: Unrecognized sub-attribute modifier (in) for business_type_id. Make sure to use a recognized sub-attribute modifier such as startsWith, <=, !, etc. )",
and if I removed where I got an error result.
please anyone have any idea or solution?
you may try with a native query as described here, https://sailsjs.com/documentation/reference/waterline-orm/datastores/send-native-query
As far as I can tell, you could simply provide an array of items. Matches against ANY of the items in the array means that the record should be returned as part of the result. Not sure if it works in a where-clause though.
Docs:Query Language (scroll to: In Modifier)
I do share your confusion as to why the given query does not work though, as the docs state that in should be valid, but perhaps it's not valid inside where:{...}? And I am assuming you are using .find() inside .Get(...)? Simply proxying the query unchanged through to .find()?
filterShopType(){
this.service.serviceName = 'fairCustomers';
this.service.Get({
populate:'country_id, business_type_id',
business_type_id: this.business_ids_filter,
limit:20
})
.then((data: any) => {
this.fairCustomers.splice(0, this.fairCustomers.length);
this.fairCustomers.push(data);
this.Refresh('fairCustomers');
}).catch((err) => {
console.log('failed get fairCustomers from server ', err);
});
}
Now, you of course need to make sure that the array actually is an array if you use in:.
It is working with me by using [or] instead of [in], this is the code
filterShopType(){
if(this.business_ids_filter){
this.service.serviceName = 'fairCustomers';
var arr = [];
this.business_ids_filter.forEach( (id) => {
arr.push({ business_type_id: id })
});
let where = {};
if(arr.length > 0){
where = {or: arr};
}
this.service.Get({ populate: 'country_id,business_type_id',where:where , limit:20 }).then((data: any) => {
this.filterItems.splice(0, this.filterItems.length);
this.filterItems.push(data);
this.Refresh('filterItems');
}).catch((err) => {
console.log('failed get fair Customers from server ', err);
});
}else{
this.set('isFilter', false);
}
}

ES6 curly braces usage when extracting from an object and assigning to another object

I would like to use curly braces to replace this code:
let rUsers = children.map((user) => {
let rUser= {};
rUser.firstName = user.firstName;
rUser.lastName = user.lastName;
rUser.relation = user.patron.relation;
return rUser;
});
This is what I have:
let rUsers = children.map((user) => {
let rUser = {};
({
firstName: rUser.firstName,
lastName: rUser.lastName,
patron.relation: rUser.relation, // I get an error here
} = user);
return rUser;
}
Except for patron.relation, the rest of the extraction works.
Questions:
How should I extract value of user.patron.relation?
Is there a more succint way of writing the above?
Thanks!
How should I extract value of user.patron.relation?
You would use { … patron: {relation: rUser.relation}, … } as the destructuring target.
Is there a more succint way of writing the above?
If the property names don't match there's not much you can do, but in your particular case you can simplify by destructuring the parameter into multiple variables:
const rUsers = children.map(({firstName, lastName, patron: {relation}}) =>
({firstName, lastName, relation})
);
You can use object destructuring like this:
const {firstName, lastName, patron: {relation}} = user
And relation has been set to the value of user.patron.relation.
You can return the object you want like so:
return {firstName, lastName, relation}
I'm seeing a few things wrong with your code.
patron.relation -> patron isn't defined, and can't be used as a key.
In the second example, rUser is used - I think you just want user.
My understanding of what you're trying to do essentially create a clone? If so, you should be able to do something like this.
let rUsers = children.map(user => {
firstName: user.firstName,
lastName: user.lastName,
relation: user.relation
});
Alternatively, it could be simpler to use Object.assign()
let rUsers = children.map(user => Object.assign({}, user));