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!