TypeOrm only retrieve one Field in leftJoinAndSelect - relationship

I've read documention typeorm, but un didn't find the solution of my problem.
Neither in the forum, somme guys describe suquery, but it's not works with leftJoinAndSelect.
If someone can help thanks a lot
I've Article entity
#Entity('article')
export class Article extends BaseEntity{
#PrimaryGeneratedColumn()
id: number;
#Column()
title: string;
#Column({type: "longtext"})
content: string;
#Column({ default: false })
is_published: boolean;
#CreateDateColumn({ type: "timestamp", default: () => 'CURRENT_TIMESTAMP' })
createDateTime: Date;
#ManyToOne(type => User, user => user.articles)
user:User;
}
and User entity
#Entity()
export class User extends BaseEntity{
#PrimaryGeneratedColumn()
id: number;
#Column()
username: string;
#Column()
password: string;
#Column({ default: true })
isActive: boolean;
#Column({default: 'contrinutor'})
role: string
#OneToMany(()=> Article, article => article.user)
articles: Article[];
}
I want to get one article and join the user associate to the article, BUT only retrieve data for the article and the username , NOT all info data.
Currently i 've tried this:
const article = await this.articleRepository
.createQueryBuilder('article')
.where({id: id})
.leftJoinAndSelect("article.user","user")
.getOne();
And result :
{
"id": 1,
"title": "My super Title",
"content": "My super content",
"is_published": false,
"createDateTime": "2021-01-21T13:37:15.894Z",
"user": {
"id": 1,
"username": "admin",
"password": "admin",
"isActive": true,
"role": "contributor"
}
}
and that i would wish:
{
"id": 1,
"title": "My super Title",
"content": "My super content",
"is_published": false,
"createDateTime": "2021-01-21T13:37:15.894Z",
"user": {
"username": "admin",
"role": "contrinutor"
}
}
Thanks for help 😁

You can Archive the result by using select,leftJoin and AddSelect :
const article = await this.articleRepository
.createQueryBuilder('article')
.where({id: id})
.leftJoin("article.user","user")
.select(['article'])
.addSelect(['user.username','user.role'])
.getOne();

Related

Working on a React project and getting error on TS

I am working on a react project and I am new to TS.
Below is my code -
interface GetAllRolesResponse {
id: number;
roleName: string;
description: string;
permission: {
id: number;
component: string;
createPermission: boolean;
viewPermission: boolean;
updatePermission: boolean;
deletePermission: boolean;
}[];
}
const [rows, setRows] = useState<GetAllRolesResponse[]>(INITIAL_DATA);
And INITIAL_DATA looks like this -
"INITIAL_DATA": [
{
"id": 1,
"roleName": "Client Admin",
"description": "This is a client admin",
"permission": [{
"id": 1,
"component": "Client",
"createPermission": true,
"viewPermission": true,
"updatePermission": true,
"deletePermission": true
}]
},
{
"id": 2,
"roleName": "Annotator",
"description": "This is Annotator",
"permission": [{
"id": 1,
"component": "Client",
"createPermission": true,
"viewPermission": true,
"updatePermission": true,
"deletePermission": true
}]
},
]
I am setting my setRows like this -
const roles = useSelector(allRoles);
useEffect(() => {
setRows(roles);
setLoader(false);
}, []);
I am getting a TS error here -
Not sure what I am missing here.
You defined your state as an array of GetAllRolesResponse, but you're trying to update it to be just one instance of GetAllRolesResponse
If you want to replace the state with the value returned from useSelector(allRoles), you should make sure that returns an array.
If you want to update the state to add the return of useSelector(allRoles), try this instead:
const roles = useSelector(allRoles);
useEffect(() => {
setRows((r) => [...r, roles]);
setLoader(false);
}, []);
Here you'd be creating a new array (never mutate state) with whatever was already in it (...r) plus the new roles.

Fetching and organizing data and rendering the response

total noob looking for some help with react and handling data from a response.
When data is structured like this I have no problem - I can render it just fine.
[{
"id":"90",
"symbol":"BTC",
"name":"Bitcoin",
"nameid":"bitcoin",
"rank":1,
"price_usd":"42674.97",
"percent_change_24h":"-3.66",
"percent_change_1h":"0.71",
"percent_change_7d":"-10.16",
"market_cap_usd":"803057883424.85",
"volume24":"36258318378.29",
"volume24_native":"849639.08",
"csupply":"18818009.00",
"price_btc":"1.00",
"tsupply":"18818009",
"msupply":"21000000"
}]
like such
this.state = {
coins: [] ...
<h1 key={coins.id}> {coins.name} {coins.price_usd} </h1>
However when it's an array of lists like this I have a problem.
{
"data": [
{
"id": "bitcoin",
"rank": "1",
"symbol": "BTC",
"name": "Bitcoin",
"supply": "17193925.0000000000000000",
"maxSupply": "21000000.0000000000000000",
"marketCapUsd": "119150835874.4699281625807300",
"volumeUsd24Hr": "2927959461.1750323310959460",
"priceUsd": "6929.8217756835584756",
"changePercent24Hr": "-0.8101417214350335",
"vwap24Hr": "7175.0663247679233209"
},
{
"id": "bibox-token",
"rank": "100",
"symbol": "BIX",
"name": "Bibox Token",
"supply": "102339166.0000000000000000",
"maxSupply": null,
"marketCapUsd": "72116102.5394724649666992",
"volumeUsd24Hr": "45084130.4166935808283857",
"priceUsd": "0.7046774500729512",
"changePercent24Hr": "-3.0331628584946192",
"vwap24Hr": "0.7207903092174193"
}
],
}
when I see anything that is prefixed with "data:[{... I stumble I think it has todo with coins: [], do I set the state with data.coins?.
I was raised to think there are no dumb questions... however I really feel like I'm overlooking something simple and my brain hurts.
If you are getting response like data: [{id:1,...}, {id:2,...}]
You need set your response to your state like this.setState({ coins: response.data })
Here an example
const response = {
data: [
{
id: "bitcoin",
rank: "1",
symbol: "BTC",
name: "Bitcoin",
supply: "17193925.0000000000000000",
maxSupply: "21000000.0000000000000000",
marketCapUsd: "119150835874.4699281625807300",
volumeUsd24Hr: "2927959461.1750323310959460",
priceUsd: "6929.8217756835584756",
changePercent24Hr: "-0.8101417214350335",
vwap24Hr: "7175.0663247679233209"
},
{
id: "bibox-token",
rank: "100",
symbol: "BIX",
name: "Bibox Token",
supply: "102339166.0000000000000000",
maxSupply: null,
marketCapUsd: "72116102.5394724649666992",
volumeUsd24Hr: "45084130.4166935808283857",
priceUsd: "0.7046774500729512",
changePercent24Hr: "-3.0331628584946192",
vwap24Hr: "0.7207903092174193"
}
]
};
constructor(props) {
super(props);
this.state = {
coins: []
};
}
componentDidMount() {
this.setState({ coins: response.data });
}
You can access data by this.state.coins[0].name or map()

MongoDB: How can I add an Object into an array?

I have been working with MongoDB and I have a requirement that I don't know how to solve with this technology.
Maybe with an example it will be better understood.
I have two interfaces like this:
export interface Alumn{
id: string;
name: string;
age: number;
}
export interface Class{
id: string;
room: number;
alumns: [
member: Alumn; (Referencing the other interface)
]
}
And what I want to do is add that Alumn object into the array that belongs to the Class interface with MongoDB.
id: string;
room: number;
alumns: [
member: {id, name, age}
]
Thanks in advance.
Use $push
db.collection.update(
{
_id: 1
},
{
$push: {
albums: {
$each: [
{
"id": 1,
"name": "a",
"age": 10
}
]
}
}
})
Example:mongoplayground

How to normalize the data from the JSON with normalizr?

I am quite new to the normalizr and can't understand it well enough yet. How can I normalize the following JSON response so it can be used for the Redux:
{
"statusCode":200,
"message":"Random quotes",
"pagination":{
"currentPage":1,
"nextPage":null,
"totalPages":1
},
"totalQuotes":1,
"data":[
{
"_id":"5eb17aadb69dc744b4e70e05",
"quoteText":"One crowded hour of glorious life is worth an age without a name.",
"quoteAuthor":"Walter Scott",
"quoteGenre":"age",
"__v":0
}
]
}
It would be useful to put the data object at the top level in the normalized object.
How can I combine this with TypeScript?
Thank you in advance.
Typescript types can definitely help you to understand the data that you are dealing with. You want to describe various pieces of the response with their own types and then piece them together.
interface Quote {
_id: string;
quoteText: string;
quoteAuthor: string;
quoteGenre: string;
__v: number;
}
interface Pagination {
currentPage: number;
nextPage: null | number; // what is this when it's not null?
totalPages: number;
}
interface APIResponse {
statusCode: number;
message: string;
pagination: Pagination;
totalQuotes: number;
data: Quote[];
}
normalizr isn't super helpful here because you only have one entity type which is a Quote. In a sense you have two entity types if you are treating the response itself as an entity. But I'm not sure how you would extract a unique id from it. You'd probably have to add it yourself based on the API path/params since that information is lacking in the JSON.
const quote = new schema.Entity("quote", {}, { idAttribute: "_id" });
const response = new schema.Entity("response", {
data: [quote] // an array of quote entities
});
console.log(normalize({...json, id: "/random-quote"}, response));
This gives you
{
"entities": {
"quote": {
"5eb17aadb69dc744b4e70e05": {
"_id": "5eb17aadb69dc744b4e70e05",
"quoteText": "One crowded hour of glorious life is worth an age without a name.",
"quoteAuthor": "Walter Scott",
"quoteGenre": "age",
"__v": 0
}
},
"response": {
"/random-quote": {
"statusCode": 200,
"message": "Random quotes",
"pagination": {
"currentPage": 1,
"nextPage": null,
"totalPages": 1
},
"totalQuotes": 1,
"data": ["5eb17aadb69dc744b4e70e05"],
"id": "/random-quote"
}
}
},
"result": "/random-quote"
}

Order of data returning from Monongodb

I am making a mongodb model>>
const mongoose = require('mongoose');
const {Schema} = mongoose;
const locationSchema = new Schema({
name: String,
Address: String,
ContactInfo: {
phone: Number,
email: String,
},
Website: String,
Hours: {
DaysOpen: String,
OpeningTime:[Number],
ClosingTime:[Number],
},
Services: String,
Languages: String,
Documentation: Boolean,
OtherNotes: String,
})
mongoose.model('Locations', locationSchema);
When I try and run a get request to see what is in my database I am returned
{
"error": false,
"location": {
"Hours": {
"OpeningTime": [
1215,
898
],
"ClosingTime": [
1400
],
"DaysOpen": "Sunday"
},
"_id": "5ee8fd2e57aa5126d4c1c854",
"name": "Evergreen Christian Center Food Pantry",
"Address": "4400 NW Glencoe Rd, Hillsboro, OR 97124",
"ContactInfo": {
"phone": 5033196590,
"email": "gonzocyn2#msn.com"
},
"Website": "https://www.ecc4.org/home",
"Services": "All foods available including meat and frozen foods",
"Languages": "English, Spanish",
"Documentation": false,
"OtherNotes": "Bring own bag or box. Sign up starts at 9:00am",
"__v": 0
}
The problem is that "Hours" is being displayed before the name, address, and contact info. This only occurs when I have the fields "OpeningTime" and "ClosingTime" as arrays. Any idea on how to fix this?

Resources