The Sequelize upsert() function will always insert new records and never performs updates

:

While attempting to utilize model.upsert() within sequelize, I am consistently experiencing insertions, regardless of any modifications made to the query.

I have a Transaction model that comprises various fields, including the default generated id.

Upon reviewing the documentation for upsert in sequelize, it became apparent that:

An update will occur if a row matching the supplied values on either the primary key or a unique key is discovered. It's important to define the unique index in your sequelize model rather than solely in the table.

My assumption was that defining the id of the Transaction in the model definition would be necessary, so I proceeded accordingly without success as it continues to create new entries exclusively...

TransactionModel = {
    id: {
        type: Sequelize.INTEGER,
        allowNull: false,
        primaryKey: true,
        autoIncrement: true
    },
    {.......}
}

Where could I be going wrong? What might I have overlooked?

Any insights and resolutions would be greatly appreciated. Thank you in advance!

EDIT:

The upsert code utilized is:

createOrUpdateTransaction: {
            type: Transaction,
            args: {
                payerAccountNumber: {type: new GraphQLNonNull(GraphQLInt)},
                recipientAccountNumber: {type: new GraphQLNonNull(GraphQLInt)},
                amount: {type: new GraphQLNonNull(GraphQLFloat)},
                currency: {type: new GraphQLNonNull(GraphQLString)},
                paymentMethod: {type: new GraphQLNonNull(GraphQLString)},
                cardNumber: {type: GraphQLFloat},
                cardName: {type: GraphQLString},
                cardNetwork: {type: GraphQLString},
                cashMachineId: {type: GraphQLFloat},
                receiptNumber: {type: new GraphQLNonNull(GraphQLFloat)},
                invoiceNumber: {type: new GraphQLNonNull(GraphQLFloat)},
                receiptCopy: {type: new GraphQLNonNull(GraphQLString)},
                description: {type: GraphQLString},
                bankDescription: {type: GraphQLString},
                bankReference: {type: new GraphQLNonNull(GraphQLString)},
                bankSubCurrencyAccount: {type: new GraphQLNonNull(GraphQLString)},
                tags: {type: new GraphQLList(GraphQLString)},
                notes: {type: GraphQLString}
            },
            resolve: (root, args) => {
                return db.models.transaction.upsert({
                    time: new Date().toString(),
                    payerAccountNumber: args.payerAccountNumber,
                    recipientAccountNumber: args.recipientAccountNumber,
                    amount: args.amount,
                    currency: args.currency,
                    paymentMethod: args.paymentMethod,
                    cardNumber: args.cardNumber,
                    cardName: args.cardName,
                    cardNetwork: args.cardNetwork,
                    cashMachineId: args.cashMachineId,
                    receiptNumber: args.receiptNumber,
                    invoiceNumber: args.invoiceNumber,
                    receiptCopy: args.receiptCopy,
                    description: args.description,
                    bankDescription: args.bankDescription,
                    bankReference: args.bankReference,
                    bankSubCurrencyAccount: args.bankSubCurrencyAccount,
                    tags: args.tags,
                    notes: args.notes,
                    bankAccountAccountNumber: args.payerAccountNumber
                })
            }
        }

This is part of a Mutation within GraphQL.

It should be noted that this previously functioned as addTransaction, and the only alteration made was switching from db.models.transaction.create() to db.models.transaction.upsert().

Answer №1

When looking at your upsert() example, it's clear that the id of the entry is not provided in the method. Because of this, Sequelize is unable to match the id to a row (as the id is undefined), resulting in the insertion of a new row.

Even if a different primary key is used, it must always be a property in order to find a match, as Sequelize relies on the primary key to locate an existing row.

createOrUpdateTransaction: {
    type: Transaction,
    args: {
        // Omitted code...
    },
    resolve: (root, args) => {
        return db.models.transaction.upsert({
            // The id property needs to be included in the args object
            // for a match to an existing row. If args.id is missing, 
            // a new row will be inserted.
            id: args.id, 
            time: new Date().toString(),
            payerAccountNumber: args.payerAccountNumber,
            recipientAccountNumber: args.recipientAccountNumber,
            amount: args.amount,
            currency: args.currency,
            paymentMethod: args.paymentMethod,
            cardNumber: args.cardNumber,
            cardName: args.cardName,
            cardNetwork: args.cardNetwork,
            // Omitted fields ...
        })
    }
}

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

Is it necessary to match GET and POST routes only if a static file does not match?

I am encountering an issue with my routes and static definitions in Express. Here is my route setup: app.get('/:a/:b/:c', routes.get); Along with this static definition: app.use('/test', express.static(__dirname + '/test')); ...

SQL Server is throwing an error because it can only accept one expression in the select list when the subquery is introduced without using exists

I'm encountering an issue when trying to execute my query. Here is the query I am running: if exists (select CODE_ISIN from cte where code_ISIN not in (select [STATUT_TITRE], [CODE_ISIN] fr ...

ASP.NET User Creation Tool - Tailoring assistance

I have implemented the ASP membership feature to enable user management on my website. I customized the default tables by adding a few extra fields. To enhance the user creation process, I transformed the first step of the wizard into an editable template ...

What could be causing my completed torrents to sometimes not be saved to my disk?

Currently, I am working on developing a small torrent client using electron and webtorrent. Although everything appears to be functioning correctly initially, there is an issue where sometimes the resulting files from a finished download are not being save ...

Determine the number of unique user IDs across various tables

I have five tables, each with a common field called "userid." My goal is to count the number of distinct userids across all five tables. Some user ids may appear in multiple tables, but I want to count the union of all distinct user ids in the five table ...

GCP BigQuery - Optimizing Full Table Reads with LIMIT - Learn how to minimize queried data for faster results

It seems that adding a LIMIT to the query would not impact the amount of data processed/queried, based on what the UI is showing. https://i.sstatic.net/FLolo.png SELECT * --count(*) FROM `bigquery-public-data.github_repos.commits` -- LIMIT 20 Is t ...

Upgrading object based on dynamic data shifts in Vue using Vuex

My current task involves updating data in a component based on the selection made from a tabs list at the top of the page. The data is sourced from a Vuex data store, and after conducting tests on the data store, everything appears to be functioning correc ...

Exploring JSON Data with D3 through Dynamic Jumps

I'm currently delving into the realm of D3 visualization and I have a feeling that there might be a solution out there for what I'm attempting to achieve. Let's assume I have JSON data structured like this: var arr = [ { "name" ...

Guide to uploading a PDF to Google Drive and embedding it on an HTML static website

I manage a static HTML site for a small food shop. They require monthly menu uploads in PDF format. I believe uploading to Google Drive would be a more efficient solution than creating a separate admin view for file uploads. Can anyone advise me on how to ...

Display information from a mysql database table within a selection menu

Currently, I am working on a dropdown menu that should display data from a MySQL table. However, I am facing an issue which is outlined below: In my PHP script, I have approached it in the following manner: <label class="col-form-label" for="formGrou ...

Sending a JSON object as a parameter in JavaScript with whitespace within the data

It appears that the code is functional when there are no spaces in the content <a onclick=fbShareDialog("{\"name\":\"aaaaaaa\"}"> However, if there is a space present <a onclick=fbShareDialog("{\"name\":\"bbbb ...

Stack screen not visible on React Native navigation

I'm currently utilizing the React Native Navigation library for routing. However, I've encountered an issue with the code below that doesn't seem to be functioning as expected. My objective is to set up two screens - one for login and the o ...

Encountering "Cannot GET" error following asynchronous AJAX call in ReactJS react.Component

I'm encountering a problem with my reactjs code. After addressing issues related to asynchronous operations, I now face a blank page with an error message saying "Cannot GET /thenameofthepage." Here is the code snippet following the react.Component: ...

Recurring occurrences of Ajax ViewComponent being triggered

I have encountered a problem with an on-click Ajax event that is triggering a Controller action/ViewComponent multiple times. The issue arises when I utilize Ajax on a button click to call a Controller Action, which inserts data into the database and then ...

Tips for eliminating duplicate rows from a join query in mysql

Currently, I have a table with columns 'id' and 'name'. There are 3 records in this table: id name 1 Chinmoy 2 Amit 3 Bhagi My desired result is as follows: name1 name2 Amit Bhagi Amit Chin ...

Understanding the functionality of app.locals within app.get in an Express application and how to effectively parse data

I am currently developing a parse application using express. In my index file, I want to display different information to users based on whether they are logged in or not. However, I am facing an issue with storing the flag and logged-in user name using ap ...

Utilizing the Input method in Node.js

Transitioning from Python 3 to Node.js has me wondering if there is a similar function in Node.js to Python's input. For example, consider this code snippet: function newUser(user = null, password = null) { if (!user) user = prompt("New user name ...

Matching objects in an array based on a specific property using the key of another object

To display information in the UI based on matching values between the data.examples array object's name.value property and the keys in the wcObject.notCoveredList, we need to create a logic. If there is a match, all corresponding values from wcObject ...

Is it necessary for me to validate the type before making each database request?

Currently, I am in the process of honing my error-handling skills within Express while using a Postgres database. My backend code consists of numerous small functions that serve as intermediaries for handling interactions with the database in larger funct ...

Tips on how to modify database records rather than generating new ones

Currently, my team is developing a web application that utilizes wearables to monitor vital parameters. As part of our integration testing, we are using a Fitbit device. The app itself is built with Angular and JavaScript, while the database is hosted on C ...