Adding to an existing array in SQLite by updating a column using Sequelize

My code includes a model definition for saving product data using Sequelize:

This is how the Product model looks:
import {Optional, Model, Sequelize, DataTypes } from 'sequelize';

/*This is the Product model used to save the data about products*/
export interface ProductAttributes {
    productId: number;
    title: string;
    userName: string;
    sellerReview: string;
}

export interface ProductCreationAttributes extends Optional { }

export class Product extends Model implements ProductAttributes {
    productId!: number;
    title!: string;
    userName!: string;
    sellerReview: string;

    public static initialize(sequelize: Sequelize) {
        Product.init({
            productId: {
                type: DataTypes.INTEGER,
                autoIncrement: true,
                primaryKey: true,
            },
            title: {
                type: DataTypes.STRING,
                allowNull: false
            },
            userName: {
                type: DataTypes.STRING,
                allowNull: false
            },
            sellerReview: {
                type: DataTypes.STRING,
                get: function () {
                    return JSON.parse(this.getDataValue('sellerReview'));
                },
                set: function (val) {
                    return this.setDataValue('sellerReview', JSON.stringify(val));
                }
            }
        },
            {
                sequelize,
                tableName: 'products'
            }
        );
    }
}

In my controller, I handle inserting and updating values in the model:

This is the controller part where new products/services are added and existing products are edited:
import express from 'express';
import { Router, Request, Response, RequestHandler } from 'express';
import { Product } from '../models/product.model';
import { Readable } from 'stream';
import { Sequelize, where } from 'sequelize';

/**
 * This method is to add new products/services to the products model.
 */
productController.post('/add',
    (req: Request, res: Response) => {
        Product.create(req.body)
        .then(product_added => res.send(product_added))
        .catch(err => res.status(500).send(err));
    });

/**
 * This method is to edit a product in the products model.
 */
productController.put('/edit/:id', (req: Request, res: Response) => {
    Product.findByPk(req.params.id)
        .then(found => {
            if (found != null) {
                found.update(req.body).then(() => {
                    res.status(200).send('Product updated successfully.');
                });
            } else {
                res.status(404).send('Product not found.');
            }
        })
        .catch(err => res.status(500).send(err));
    });

// Additional update function for adding a new review
productController.put('/addNewReview/:id', (req: Request, res: Response) => {
    // Logic for adding a new review to an existing product
});

export const ProductController: Router = productController;

I have a specific requirement to concatenate a new review to the existing 'sellerReview' column value when updating. Unfortunately, using 'Sequelize.literal' did not work as intended. Can anyone offer assistance with this issue?

Thank you!

Answer №1

When utilizing the setter and getter for the sellerReview field, it restricts the use of Sequelize.literal or Sequelize.fn.

To work around this limitation, you can extract the current value of sellerReview from found and append a new value to it like so:

found.update({sellerReview: found.sellerReview.concat(req.body.sellerReview)}, { where: {productId: req.params.id}})

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

Angular2 encountering an unidentified Auth2 Object during logout process

Greetings, I am currently experiencing an issue with signing out of an auth2 client. Previously, this process functioned correctly until I upgraded my router to comply with new RC requirements. Now, it seems that the auth2 object is being cleared or lost ...

Incorporating a new method into the Object prototype to provide universal access across all modules

I've been delving into Typescript experimentation and I'm attempting to enhance the Object prototype by adding a property that can be accessed by all objects within my modules. Here's what I've developed so far: In a Common.ts file O ...

Creating a new endpoint within the Angular2 framework using typescript

I am brand new to Angular2 and I would like to streamline my API endpoints by creating a single class that can be injected into all of my services. What is the most optimal approach for achieving this in Angular2? Should I define an @Injectable class sim ...

Introducing Vee Validate 3.x and the ValidationFlags data type definition

I'm currently struggling to locate and utilize the ValidationFlags type within Vee-Validate 3. Despite my efforts, I am encountering difficulties in importing it. I am aware that this type is present in the source code located here. However, when I a ...

What is the solution for resolving an Element that implicitly has said it has an 'any' type as the expression of type 'string' cannot be used to index the type?

Having some trouble with TypeScript in my React project and encountering this error message. Error TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ paymentMethod ...

How can you retrieve the property value from an object stored in a Set?

Consider this scenario: SomeItem represents the model for an object (which could be modeled as an interface in Typescript or as an imaginary item with the form of SomeItem in untyped land). Let's say we have a Set: mySet = new Set([{item: SomeItem, s ...

What is the method for passing an element in Angular2 Typescript binding?

Is there a way to retrieve the specific HTML dom element passed through a binding in Angular? I'm having trouble figuring it out, so here is the relevant code snippet: donut-chart.html <div class="donut-chart" (donut)="$element"> ...

Testing Next.js's getServerSideProps function with Jest: A Step-by-Step Guide

I want to conduct Jest and Enzyme tests on the Next.js getServerSideProps function. This function is structured as follows: export const getServerSideProps: GetServerSideProps = async (context) => { const id = context?.params?.id; const businessName ...

Centralized MUI design for varying screen dimensions

I am struggling to perfectly center my modal box in the middle of the screen. The problem arises when the screen size changes, causing the box to be misaligned. I attempted using top:50% and left: 50%, but this did not effectively center the box. center ...

How to include extra data in Angular Firebase user creation using the createUserWithEmailAndPassword

Currently, I am working on implementing the Firebase createUserWithEmailAndPassword method. However, I would like to include an additional field named 'name' in Cloud Firestore. Below is a snippet of my code: auth.service.ts SignUp(email: string ...

Guidelines on incorporating emotion/styled into React applications with TypeScript

Including my root component in the ThemeProvider from @emotion/react has granted me access to props.theme. Here is an example: const StyledDiv = styled.div` background-color: ${(props) => props.theme.palette.primary.main}; `; Issue: TypeScript indica ...

Typegoose's representation of modifying data

Recently, I delved into the world of NestJS and kickstarted a sample project. To integrate MongoDB seamlessly, I opted for Typegoose. A useful online tutorial () caught my eye, illustrating how to employ abstractions with base typegoose models. Hence, my ...

Implementing OTP input using Material UI textfield

Is it possible to create an OTP input using the textfield component of material UI in a React TypeScript project? I've seen examples where people have implemented this with regular input fields, but I'm specifically interested in utilizing the te ...

The issue of Angular 9 not recognizing methods within Materialize CSS modals

I am currently working on an Angular 9 application and have integrated the materialize-css 1.0 library to incorporate a modal within my project. Everything works smoothly in terms of opening and instantiating the modal. However, I have encountered an issue ...

Develop an "Import Interface" using TypeScript

I have a large project with many files and I believe using an import object would be beneficial. For instance, consider having menu.ts at the top level that every program will refer to: import router from "./router/index"; import controllers from ...

The upload cannot be completed as the file upload is not in a multipart request format

This file upload code was referenced from this source. The issue lies in the fact that it is sending the request as JSON instead of multipart form data, causing the server side code to reject the request and resulting in a failed upload. I have confirmed ...

The trouble with React Navigation encountered with TypeScript: This Entity Cannot Be Invoked

Currently, I'm facing a typescript issue after upgrading to React Navigation 5. The specific error message reads: There is an issue with calling this expression. The union type '{ <RouteName extends "Stack1Screen1" | "Home&quo ...

Tips for displaying real-time data and potentially selecting alternative options from the dropdown menu

Is there a way to display the currently selected option from a dropdown list, and then have the rest of the options appear when the list is expanded? Currently, my dropdown list only shows the available elements that I can choose from. HTML: < ...

In Angular, the object may be null

click here for image Encountering an error message stating that Object is possibly 'null' when utilizing querySelector and addEventListener in Angular. ...

Issues with manipulating state using TypeScript Discriminated Unions"Incompatibility with setState

Imagine having a unique type structure like the one shown below: export type IEntity = ({ entity: IReport setEntity: (report: IReport) => void } | { entity: ITest setEntity: (test: ITest) => void }); Both the entity and setEntity fun ...