Monday, 16 October 2023

How to insert data to sql database using nodejs and sequelize?

I am creating a REST API using nodejs , express , MySql server , sequelize

I want to save the following object to my database.

let dataToSave = {

    "config": {
        "id": "1697141843496"
        "user_id": 27856,
        "imageurl": "my url",
        "name": "Ikea",
        "server": "Google",
        "size": "300x600",
        "imageWidth": "300",
        "imageHeight": "600",
        "hide_logo": 0,
        "point_color": "#1c846a",
        "pulse": true,
    },
    "points": [
        {
            "pointId": "292155",
            "x": 60.06711409395973,
            "y": 22.909698996655518,
            "tooltip": {
                "toltipId": "292155",
                "title": "Window",
                "price": "400",
                "link": "https://interactive-img.com/editimage?image_id=52711",
                "tooltipThumbnailUrl": "blob:http://localhost:4200/c5a7369a-94bc-423d-b3f3-474a30aad69f",
                "right": "",
                "left": "40%",
                "top": "18%"
            }
        },
        {
            "pointId": "216572",
            "x": 63.758389261744966,
            "y": 70.40133779264214,
            "tooltip": {
                "toltipId": "216572",
                "title": "Jiko",
                "price": "9000",
                "link": "https://interactive-img.com/editimage?image_id=52711",
                "tooltipThumbnailUrl": "blob:http://localhost:4200/6b26099d-75c2-4f1c-ba06-dd9e0cca14d4",
                "right": "",
                "left": "43.6667%",
                "top": "65.3333%"
            }
        }
    ],
}

How can I create model based on the above object ?

This is what I have tried so far.

const { DataTypes } = require('sequelize');

module.exports = model;
function model(sequelize) {
    const attributes = {
        config: {
            type: DataTypes.JSON, 
        },
        points: {
            type: DataTypes.JSON, 
        },
    };

    const options = {
        defaultScope: {
            attributes: { exclude: ['hash'] }
        },
        scopes: {
            withHash: { attributes: {} }
        }
    };

    return sequelize.define('data', attributes, options);
}


from How to insert data to sql database using nodejs and sequelize?

No comments:

Post a Comment