1

I'm building backend with Express and TypeScript. DB is Postgres, client isnode-postgres.

In DB I have tableuser_collection. This table has column collection of type JSONB. Collection column contains an array of objects like this:

{ itemGroup: 'ANIME', itemId: 55555 }

There could be a lot of objects in this array and what I need is the query that will remove object from array by id.I've already tried few queries but every time I got an error.So for now my workaround has 2 steps.First is to get full collection.

const userCollection = await db.query(  'SELECT collection FROM user_collection WHERE user_id = $1',  [1],);

Second is to filter this array and save filtered array in collection.

const updatedCollection = existedCollection.filter(  (item: any) => item.itemId !== 11111,);    db.query('UPDATE user_collection SET collection = $2 WHERE user_id = $1', [  1,  JSON.stringify(updatedCollection),]);

Is it possible to use one query and leave filtering for DB?

jonrsharpe's user avatar
jonrsharpe
123k31 gold badges277 silver badges488 bronze badges
askedAug 18, 2024 at 7:57
Stas Motorny's user avatar
1
  • 2
    Yes, it's possible, but you'd be much better off by not storing an array in each row. Store one object per row, add a newitemId column to your table.CommentedAug 18, 2024 at 10:13

1 Answer1

2

The following removes the selected items fromcollection for the specifieduser_id in a single query:

db.query("UPDATE user_collection            SET collection =              JSONB_PATH_QUERY_ARRAY(collection,                                     ('$[*] ? (@.itemId != ' || $2 || ')')::JSONPATH)            WHERE user_id = $1", [1, 11111]);
answeredAug 18, 2024 at 10:13
JohnH's user avatar
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Sign up orlog in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

By clicking “Post Your Answer”, you agree to ourterms of service and acknowledge you have read ourprivacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.