Reputation: 43
I'm new with React and Apollo applied to MongoDB and I have the following problem:
I have a table where I have (ID - ID_A - ID_B), I made a query for this one and returns me an array. After that, I have to ask in another table for each component in the Array the match with ID_A.
So I Made:
{this.props.firstGet.map((data, index) => {
const id = data.ID_A;
return (
<Query key={this.props.firstGet.id} query={QUERY} variables={{ id }}>
{({ loading, error, data }) => {
if (loading) return 'Loading...';
if (error) return `Error ${error.message}`;
this.test = this.test.concat({...data.getStartup, ...this.state.applicants[index]});
return(this.test.length === this.props.getApplicants.length ?
<LastTable startups={this.test}></LastTable>
: '')
}
}
</Query>
);
Which one is the best practice for my problem? I need the first array with a composite for each object with the answer of the second table. Is there a way to do it directly into the main state without using LastTable for example?
How I solve it: 1)Adding in MainTable MongoDB schema:
ID_A: {
type: mongoose.Schema.ObjectId,
ref: 'Table1'
}
2)In graphQl shcema: ID_A : Table1Object
3)Adding .populate('ID_A') in resolver
I will try now inserting a new one, maybe I have problems but if with the ID in that MainTable ID_A field the connection works great
Upvotes: 4
Views: 1245
Reputation: 24130
This can be handled on graphql server side. You just need to request for those dependent fields to be resolved and returned from server side.
Just for example -
1.Create schema with fields and sub fields e.g
type Person {
id: ID!
cars: [Car]
}
type Car {
id:ID!
ownerId: Int!
model: String
}
2.You need to write nested resolvers on server side
Person resolver:
import Query from './query';
import Mutation from './mutation';
export default {
Query, //<----- person query resolver
Mutation, //<----- person mutation resolver if any
Person: { . //<----- Nested fields resolver on Person
cars: (parent, args, { dataSources }) => {
const { id: ownerId } = parent;
// return from db cars owned by person
return dataSources.carAPI.getCarsByOwnerId(ownerId);
},
},
};
I am using dataSource here but you can use directly resolve from database.
3.Query on client side
export const GET_PERSON_WITH_CARS = gql`
query getPersonWithCars($id: ID!) {
person(id: $id) {
id
cars {
id,
ownerId,
model,
}
}
`
I hope it helps
Upvotes: 3