# How to query a database

**URL:** <https://community.fibery.io/t/how-to-query-a-database/5772>\
**Category:** Get Help\
**Created:** [January 30, 2024, 6:07pm UTC](https://community.fibery.io/t/how-to-query-a-database/5772 "2024-01-30T18:07:10Z")\
**Posts on this page:** 5\
**Page:** 1

<div class="post-metadata">

**Author:** ![Yuri\_BC](https://sea2.discourse-cdn.com/flex020/user_avatar/community.fibery.io/yuri_bc/32/8803_2.png) [@Yuri\_BC](https://community.fibery.io/u/Yuri_BC)\
**Post date:** [January 30, 2024, 6:07pm UTC](https://community.fibery.io/t/how-to-query-a-database/5772/1 "2024-01-30T18:07:10Z")

</div>

I am struggling to make a script that finds entities unrelated to the current entity/database, so it needs to query the database. It aims to:

1. **Initialize the Fibery Service** : Connects to the Fibery API for executing commands and queries.
2. **Query Specific Entities** : Fetches entities from the ‘Y CAS/Contact’ database where a specific checkbox field named ‘Select’ is checked.
3. **Update Entities** : For each entity retrieved by the query, it attempts to set a single select relationship field named ‘Bucket’ to a Bucket entity that the current entity in context is related to.

I’m not familiar with database queries in Fibery, any guidelines are welcome!

---

<div class="post-metadata">

**Author:** ![Chr1sG](https://sea2.discourse-cdn.com/flex020/user_avatar/community.fibery.io/chr1sg/32/3941_2.png) [@Chr1sG](https://community.fibery.io/u/Chr1sG)\
**Post date:** [January 30, 2024, 6:44pm UTC](https://community.fibery.io/t/how-to-query-a-database/5772/2 "2024-01-30T18:44:12Z")

</div>

For queries, your best bet is probably to use a GraphQl query:

`graphql(spacename: string, command: string)`

[https://the.fibery.io/@public/User\_Guide/Guide/GraphQL-Queries-255](https://the.fibery.io/@public/User_Guide/Guide/GraphQL-Queries-255)

Then you can update singularly or in batches:  
`updateEntity(type: string, id: string, values: object)`  
`updateEntityBatch(type: string, entities: object[])`

Use the auto complete to figure out the right syntax 🙂

---

<div class="post-metadata">

**Author:** ![Matt\_Blais](https://sea2.discourse-cdn.com/flex020/user_avatar/community.fibery.io/matt_blais/32/1464_2.png) [@Matt\_Blais](https://community.fibery.io/u/Matt_Blais)\
**Post date:** [January 30, 2024, 9:00pm UTC](https://community.fibery.io/t/how-to-query-a-database/5772/3 "2024-01-30T21:00:49Z")

</div>

The GraphQl API is definitely easier to figure out and use than the equally-versatile “low level” “executeSingleCommand” interface. And you can use both via curl, etc.

But the GraphQl **names** of Spaces, DBs and fields are usually different (e.g. non-alphanumeric characters are removed, capitalization is changed).

For this reason I have found it to be a big, error-prone headache to try to mix GraphQl queries with other Fibery APIs (e.g. `fibery.getEntityById()`, etc.) within automations. 😢

---

<div class="post-metadata">

**Author:** ![Yuri\_BC](https://sea2.discourse-cdn.com/flex020/user_avatar/community.fibery.io/yuri_bc/32/8803_2.png) [@Yuri\_BC](https://community.fibery.io/u/Yuri_BC)\
**Post date:** [January 30, 2024, 9:47pm UTC](https://community.fibery.io/t/how-to-query-a-database/5772/4 "2024-01-30T21:47:31Z")

</div>

Thank you both!  
I got it working in the following way:

### For who reads this in the future and wants a working example:

Goal: to automatically update the ‘Bucket’ relationship field of selected contacts in the ‘Contact’ database based on their association with a specific ‘Bucket’ entity defined in the current ‘Y Note’ entity.

Consideration: Using the standard JavaScript API in Fibery is challenging for fetching and linking unrelated entities such as in this case, a task more efficiently handled by GraphQL queries.

```auto
const fibery = context.getService('fibery');
const yNoteType = 'Yuri/Y Note'; // Replace with your actual space and type name for Y Note

async function updateContacts() {
    try {
        // Get the current Y Note entity
        const currentEntity = args.currentEntities[0];
        const yNoteEntity = await fibery.getEntityById(yNoteType, currentEntity.id, ['Bucket']);
        const bucketId = yNoteEntity['Bucket'].Id;
        console.log('Bucket Entity ID:', bucketId);

        if (!bucketId) {
            console.log('No Bucket entity found for the Y Note entity.');
            return;
        }

        // GraphQL query to fetch all contacts
        const query = `{
            findContacts {
                id
                select
            }
        }`;

        // Execute the GraphQL query
        const response = await fibery.graphql('Y CAS', query);
        console.log('GraphQL Response:', response);

        const selectedContacts = response.data.findContacts.filter(contact => contact.select);
        console.log('Selected Contacts:', selectedContacts);

        if (selectedContacts.length === 0) {
            console.log('No selected contacts found.');
            return;
        }

        // Update each contact's 'Bucket' field
        for (const contact of selectedContacts) {
            await fibery.updateEntity('Y CAS/Contact', contact.id, { 'Bucket': bucketId });
            console.log('Updated Contact ID:', contact.id);
        }

        console.log('All selected Contacts updated with Bucket.');
    } catch (error) {
        console.error('Error in script:', error);
    }
}

await updateContacts();

```

Explanation

1. **Define GraphQL Query** :

2. **Execute GraphQL Query** :  
`const response = await fibery.graphql('Y CAS', query);`  
The script executes the GraphQL query within the ‘Y CAS’ space in Fibery, gathering data about all contacts.

3. **Filter Selected Contacts** :

This part of the script identifies which contacts need their ‘Bucket’ field updated, based on the selection criteria.

---

<div class="post-metadata">

**Author:** ![Chr1sG](https://sea2.discourse-cdn.com/flex020/user_avatar/community.fibery.io/chr1sg/32/3941_2.png) [@Chr1sG](https://community.fibery.io/u/Chr1sG)\
**Post date:** [January 30, 2024, 10:10pm UTC](https://community.fibery.io/t/how-to-query-a-database/5772/5 "2024-01-30T22:10:02Z")

</div>

Fwiw, you can use filtering directly in graphql queries, which would save you a step.
