I am using graphql with express and mongoose. for some reasons, I am getting null value for embedded documents. tried both async/await and promise.
Schema.JS
const typeDefs = `
type Patient{
name:String
}
type Order {
_id: ID!
orderName: String!
orderDate: Int,
patient:Patient
}
type Query {
allOrders: [Order]
}
`;
module.exports.schema = makeExecutableSchema({
typeDefs,
resolvers
});
resolver.JS
module.exports.resolvers = {
Query: {
async allOrders() {
return await db.cpoeDataModel.CpoeOrder.find();
}
},
Order: {
patient: async (order) => {
console.log("patient Id##", order.patientId);
return await db.domainModel.Patient.findById(order.patientId);
}
}
};
the query:
{
allOrders {
orderName,
patient {
name
}
}
}
result:
{
"allOrders": [
{
"orderName": "order1",
"patient": null
},
{
"orderName": "order2",
"patient": null
}]
}
expected result
{
"allOrders": [
{
"orderName": "order1",
"patient": {
"name":"xyz"
}
},
{
"orderName": "order2",
"patient": {
"name":"xyz"
}
}]
}
the problem was with my order collection not with code. there was some reference of patient Ids that does not exist anymore. that's why getting null values that are acceptable. I was confused just bcoz it's on the top of results.
Related
I have created a plugin in the adminstration and I want to insert the manyToMany products with vehicles into Shopware 6 database. From the code below I am trying to insert '92961afbc50e4380b3af86b257630ade' into the 'product_id' column of the 'vehicles_product' table :
import template from './sw-vehicles-import.html.twig';
const { Component, Mixin } = Shopware;
Component.register('sw-vehicles-import', {
template,
inject: ['importExport', 'repositoryFactory', 'feature'],
mixins: [
Mixin.getByName('notification'),
],
metaInfo() {
return {
title: this.$createTitle()
};
},
data() {
return {
importFile: null,
repository: null,
entity: undefined,
};
},
computed: {
},
created() {
this.repository = this.repositoryFactory.create('vehicles');
},
methods: {
onStartProcess() {
this.entity = this.repository.create(Shopware.Context.api);
this.entity.categoryFilter = 'CategoryName';
this.entity.featureFilter = 'FeatureName';
this.entity.products.productId = '92961afbc50e4380b3af86b257630ade';
this.repository.save(this.entity, Shopware.Context.api);
}
}
});
The build process doesn't work, what am I doing wrong? Could you help me please ?
You need to create a new entity collection for the association if it doesn't exist yet.
const { EntityCollection } = Shopware.Data;
if (!this.entity.products) {
this.entity.products = new EntityCollection(
'/product',
'product',
Shopware.Context.api
);
}
const product = await this.repositoryFactory.create('product').get('92961afbc50e4380b3af86b257630ade', Shopware.Context.api);
this.entity.products.add(product);
this.repository.save(this.entity, Shopware.Context.api);
I am trying to get my query to react to a ref property.
https://v4.apollo.vuejs.org/guide-composable/query.html#variables
This wont work at all
const { result, variables } = useQuery(gql`
query {
episodes(page: $page) {
info {
pages
count
}
results {
name
}
}
}
`, {
page: 2
});
Tried this as well
setup() {
const currentPage = ref(1);
const { result } = useQuery(gql`
query {
episodes(page: ${currentPage.value}) {
info {
pages
count
}
results {
name
}
}
}
`);
function pageChange() {
currentPage.value += 1;
console.log(currentPage.value)
}
return { result, currentPage, pageChange };
},
This code below works for me when I input page number manually, but I want to pass the page number as variable, because my pagination page increases and I want the query to refresh.
const { result, loading } = useQuery(gql`
query {
episodes(page: 2) {
info {
pages
count
}
results {
name
}
}
}
`,
);
Can someone assist me?
In the link you gave query is followed by the query name.
const { result } = useQuery(gql`
query getUserById ($id: ID!) {
user (id: $id) {
id
email
}
}
`, {
id: 'abc-abc-abc',
})
You don’t specify the query name
Try this instead:
const { result, variables } = useQuery(gql`
query episodes($page: Int) {
episodes(page: $page) {
info {
pages
count
}
results {
name
}
}
}
`, {
page: 2
});
I don’t know what’s your schema looks like but I inferred that page is a Int. If it’s not change Int by the page type
I am working on an endpoint with Node and sequelize, which sole responsibility is to provide the tags of a provided comma separated entities ids. So the expected response is:
{
"entity1_id": ["tag1", "tag2",],
"entity2_id": ["tag3", "tag4"],
}
and i had no trouble to achieve it but I realized i was instantiating the entities in a for loop and then asking for their tags, which is horrible for performance.
So instead of doing that i decided to use a raw query:
import { QueryTypes } from "sequelize";
await this.connection.query(
`SELECT tr.external_id, ta.name from transactions tr
INNER JOIN tag_taggable tt ON tt.taggable_id = tr.id AND tt.taggable_type = '${taggableType}'
INNER JOIN tags ta ON tt.tag_id = ta.id WHERE tr.external_id IN ('${ids.join("','")}'
);`, { type: QueryTypes.SELECT });
where ids is a string[] and external_id is the identifier of the entity i'm using.
Now I get a result like this:
[
{ external_id: 'entity1_id', name: 'tag1' },
{ external_id: 'entity1_id', name: 'tag2' },
{ external_id: 'entity2_id', name: 'tag3' },
{ external_id: 'entity1_id', name: 'tag4' }
]
and I was wandering about what i need to do to acheive the response i was sending before. Something in the SQL side??, and if not, what is the best approach to do it in the JS side?? (reducer? for of?).
For the JS side i came up to a for of and a reduce
const alreadyPushedIds: string[] = [];
const finalResult: { [key: string]: string[] } = {};
for (const result of results) {
if (alreadyPushedIds.includes(result.external_id)) {
finalResult[result.external_id].push(result.tag_name);
} else {
alreadyPushedIds.push(result.external_id);
Object.assign(finalResult, { [result.external_id]: [result.tag_name] });
}
}
results.reduce<{ [key: string]: string[] }>((
acc: { [key: string]: string[] },
val: { external_id: string; tag_name: string }
) => {
if (!acc[val.external_id]) {
acc[val.external_id] = [];
}
acc[val.external_id].push(val.tag_name);
return acc;
}, {})
I'm attempting to create a "Show More" button for my posts index. The index query loads fine with the first 5 posts, when I click the Show More button I can see new posts being returned, however I receive a bunch of errors like:
Missing field id in {
"__typename": "Post",
"posts": [
{
"id": "5f2b26600c3ec47b279d8988",
"title":
I receive one of each of these errors pretty much for each post attribute (id, title, content, slug, etc). This prevents the actual new posts from being added to the index. What causes this issue?
<script>
import postsQuery from '~/apollo/queries/blog/posts';
const pageSize = 5;
export default {
name: 'BlogIndex',
data: () => ({
loadingMorePosts: false,
page: 0,
pageSize,
}),
apollo: {
postsCount: {
prefetch: true,
query: postsQuery,
variables: {
page: 0,
pageSize,
}
},
posts: {
prefetch: true,
query: postsQuery,
variables: {
page: 0,
pageSize,
}
},
},
computed: {
morePosts() {
return this.posts.length < this.postsCount.aggregate.totalCount;
}
},
methods: {
async fetchMorePosts() {
this.page += this.pageSize;
this.$apollo.queries.posts.fetchMore({
variables: {
page: this.page,
pageSize,
},
updateQuery: (previousResult, { fetchMoreResult }) => {
const newPosts = fetchMoreResult.posts;
console.log('typename: ', previousResult.posts.__typename); <--- returns undefined
if (!newPosts.length) return previousResult;
return {
posts: {
__typename: previousResult.posts.__typename,
posts: [...previousResult.posts, ...newPosts],
}
}
}
})
},
},
}
</script>
UPDATE: added imported posts query
query Posts($page: Int!, $pageSize: Int!) {
posts(
start: $page
limit: $pageSize
sort: "published_at:desc"
where: { published: true }
) {
id
title
content
slug
published
createdAt
updatedAt
published_at
}
postsCount: postsConnection(where: { published: true }) {
aggregate {
totalCount
}
}
}
I think the problem is here:
return {
posts: {
__typename: previousResult.posts.__typename,
posts: [...previousResult.posts, ...newPosts],
}
}
I'm pretty sure __typename is supposed to belong to each post object, not part of the collection of posts. Let me know how if something like this fixes it:
return {
posts: {
posts: [...previousResult.posts, ...newPosts]
}
}
and changing the query to:
query Posts($page: Int!, $pageSize: Int!) {
posts(
start: $page
limit: $pageSize
sort: "published_at:desc"
where: { published: true }
) {
__typename // add this here
id
title
content
slug
published
createdAt
updatedAt
published_at
}
postsCount: postsConnection(where: { published: true }) {
aggregate {
totalCount
}
}
}
var where = {
[Op.or]:
[
{ status: { [Op.ne]: 'disable' } },
{ status: { [Op.eq]: null } }
],
}
db.diagnostic.findAll({ where: where }).then(resp => {
res.send(resp)
})
This above code is working
but,
var where = {
status: { [Op.ne]: 'disable' } // I want use only this code instead of `or`
}
db.diagnostic.findAll({ where: where }).then(resp => {
res.send(resp)
})
I want to use only status: { [Op.ne]: 'disable' }
Model: diagnostic.js
...
status: {
type: DataTypes.STRING,
defaultValue: "enable", // <- default value will solve my problem
}
...