How to use node-postgres to delete an object from an array

Currently working on the backend using Express and TypeScript. Postgres is the chosen database with node-postgres as the client.

Within the database, there is a table called user_collection. One of its columns is collection of type JSONB, which holds an array of objects structured like this:

{ itemGroup: 'ANIME', itemId: 55555 }

This array can contain multiple objects, and I'm in need of a query that can remove an object from the array based on its id. I've attempted several queries, but keep running into errors. As a temporary solution, I have devised a two-step workaround method. The first step involves retrieving the entire collection.

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

The second step entails filtering this array and updating the filtered version back into the 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),
]);

I'm wondering if it's possible to achieve this with just one query and let the database handle the filtering process?

Answer №1

This code snippet demonstrates how to efficiently remove selected items from a database collection for a specific user ID using a single query:

db.query("UPDATE user_collection
            SET collection =
              JSONB_REMOVE_PATH_COLLECTION(collection,
                                     ('$[*] ? (@.id != ' || $2 || ')')::JSONPATH)
            WHERE user_id = $1", [1, 11111]);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Type inference and the extends clause in TypeScript 4.6 for conditional types

My focus was on TypeScript 4.7 when I created the following types: const routes = { foo: '/foo/:paramFoo', bar: '/bar/:paramFoo/:paramBar', baz: '/baz/baz2/:paramFoo/:paramBar', } as const; type Routes = typeof routes; ...

Managing non-mandatory information in a structured domain representation: What's the best approach?

When working on applications or domain models, I often ponder the most effective approach to handling incomplete or optional data. Typed languages like TypeScript and C# offer the advantage of defining models with strict types. While this can be beneficial ...

Make sure to implement validations prior to sending back the observable in Angular

Each time the button is clicked and if the modelform is invalid, a notification message should be returned instead of proceeding to create a user (createUser). The process should only proceed with this.accountService.create if there are no form validation ...

transferring information from Node.js/MongoDB to the front-end (invisible in the browser)

I am trying to retrieve data from a mongodb database and pass it to the front-end. The function I have written works in the console, where I can see an array containing elements. However, when I try to view it in the browser, it shows undefined. I am worki ...

When I select a link on the current page, I would like the information in the input fields to be cleared

Currently using Angular 8, I recently included onSameUrlNavigation: 'reload' to my router. This change has successfully allowed the page to reload upon a second click on the same link. However, I've noticed that the input fields on the reloa ...

Execute service operations simultaneously and set the results in the sequence they are received

I am faced with a challenge involving multiple service methods that fetch data from various servers. The responses from these APIs come in at different times, and I need to store the responses in variables as soon as they are received. Here are my service ...

Enhancing the Value of BehaviorSubject with Object Assign in Angular using Typescript and RxJs

I have a user object stored as a BehaviorSubject which is being observed. I need help figuring out how to detect if a specific value within my user object has changed. I've noticed that my current implementation doesn't seem to work correctly, a ...

Is it possible to handle both ajax form submissions and browser post submissions in express.js?

On my website, I have implemented a contact form using express.js (4.0). I am contemplating how to manage the scenario where a user disables JavaScript. If the last part of my routing function looks like this: res.render('contact.jade', { tit ...

I encounter an issue when trying to declare an enum in TypeScript

At line 26 in my typescript file, the code snippet below shows an enum definition: export enum ItemType { Case = 'Case', Study = 'Study', Project = 'Project', Item = 'Item', } I am currently using Visual Stu ...

What could be the reason for an async function to send an empty object in the request body?

I'm currently utilizing nuxt.js, mongoDB, express, and bodyParser as well Unfortunately, the solutions provided by others do not solve my issue, as having bodyParser does not seem to fix it. The uploadPet function is designed to collect form data an ...

Creating a new document or collection by posting an aggregation

Currently, I am working with a client where a form is submitted and stored in a Mongo database. I have performed an aggregation to identify individuals who have selected the same place, date, and time. My goal now is to create a Mongo document that stores ...

Guide to importing JavaScript in an npm package using TypeScript and JavaScript

I recently downloaded a library that includes both Typescript and its corresponding javascript version. Despite trying to declare import Library from "@scope/library", my application is only able to access the Typescript version, even after adding the .js ...

Utilizing auto-generated Nonce for Content Security Policy in a Node.js/Express web application

I've exhausted all possible solutions in my attempt to create a nonce and pass it successfully to the CSP and inline scripts with the nonce variable. Despite reading numerous articles, the guidance on accomplishing this task remains vague. Fortunately ...

Disregarding text within an express route

I am currently working with the following routes: app.get('/blah/query.json', doSomething); app.get('/blah/:id.:format', doSomethingElse); At the moment, both routes are being triggered so that route one (query.json) is called first f ...

Increase the totalAmount by adding the product each time

Can someone help me understand why the totalAmount shows as 20 when I add a product? Also, why doesn't it increase when I try to increment it? Any insights would be appreciated. Thank you. ts.file productList = [ { id: 1, name: 'Louis ...

An express.js mishap occurred when attempting to process an HTTP POST request using an AJAX client-side, resulting in a

Encountering a 500 Internal Server Error when attempting to send an HTTP POST request from client-side JavaScript using JQuery AJAX in Express.js. The code resides in the p.js file on the client. function dataHandler(conn,data) { var datalol=data; ...

The rendering process failed when trying to deploy the backend

add image description here Currently, my backend is built using node.js with the express and mongoose packages connected to a MongoDB database. However, I encountered an error while deploying my backend on Render. ...

navigating to a different route handler in express without triggering a redirect

Here is the code snippet I am working with: app.get('/payment', function(req, res) { // do lots of stuff }); Now, I would like to include the following: app.post('/payment', function(req, res) { req.myvar = 'put something he ...

Analyzing User Input and Database Information with Mongodb

Here's the HTML form I'm working with: <form id="contact-form" method="POST" action="/search"> <label for="company">Phone company</label> <input type="text" name="company" value=""> &l ...

Utilizing objects as values with `react-hook-form`

About the Issue I'm facing an issue with a component that utilizes an object as its value. My goal is to integrate this component with react-hook-form The challenge arises when react-hook-form considers my object as a nested form control Background ...