Using Sequelize's association include results in a null value being returned

I am encountering an issue while attempting to link a table in my query using sequelize-cli.

Although my query functions correctly, it fails to populate the Adresse table. Only Patient gets populated, while Adresse array is overlooked and returns null.

I have established a one-to-one relationship between the tables, but I am uncertain whether this is the cause of the error or if the issue lies elsewhere in how I am associating the two tables.

Below are my models :

server/models/patient.js

module.exports = (sequelize, Sequelize) => {
    const Patient = sequelize.define('Patient', {
        ///
    }, {
        classMethods: {
            associate: (models) => {
                Patient.belongsTo(models.Adresse, {
                    foreignKey: 'adresseId',
                });
            }
        }
    });
    return Patient;
};

server/models/adresse.js

module.exports = function(sequelize, Sequelize) {
    const Adresse = sequelize.define('Adresse', {
        adresse: {
            type: Sequelize.STRING,
            allowNull: false,
        },
        complementAdr: {
            type: Sequelize.STRING
        },
        codePostal: {
            type: Sequelize.INTEGER,
            allowNull: false
        },
    }, {
        classMethods: {
            associate: (models) => {
                Adresse.hasMany(models.Patient, {
                    foreignKey: 'adresseId',
                    as: 'Patients',
                });
            }
        }
    });
    return Adresse;
};

and this is where I specified the association in my migration files :

server/migrations/20170326145609-create-patient.js

adresseId: {
    type: Sequelize.INTEGER,
    references: {
        model: 'Adresses',
        key: 'id_adresse',
        as: 'adresseId',
    },
},

server/migrations/20170326145502-create-adresse.js

module.exports = {
    up: (queryInterface, Sequelize) => {
        return queryInterface.createTable('Adresses', {
            id_adresse: {
                allowNull: false,
                autoIncrement: true,
                primaryKey: true,
                type: Sequelize.INTEGER
            },
            adresse: {
                type: Sequelize.STRING,
                allowNull: false,
            },
            complementAdr: {
                type: Sequelize.STRING
            },
            codePostal: {
                type: Sequelize.INTEGER,
                allowNull: false
            },
            createdAt: {
                allowNull: false,
                type: Sequelize.DATE
            },
            updatedAt: {
                allowNull: false,
                type: Sequelize.DATE
            }
        });
    },
    down: function(queryInterface, Sequelize) {
        return queryInterface.dropTable('Adresses');
    }
};

Lastly, here is the query in my controller file :

server/controllers/patients.js

const express = require('express');
const router = express.Router();
const jwt = require('jsonwebtoken');
const Patient = require('../models').Patient;
const Adresse = require('../models').Adresse;

module.exports = {
    create(req, res) {
        return Patient
            .create({
                ///
                adressesId: {
                    adresse: req.body.adresse,
                    codePostal: req.body.codePostal,
                }
            }, {
                include: [{
                    model : Adresse
                }]
            })
            .then(patient => res.status(201).send(patient))
            .catch(error => res.status(400).send(error));
    }
};

Answer №1

Consider using Address instead of addressId when eagerly creating the Address model instance associated with the provided Patient

return Patient.create({
    // patient attributes,
    Address: {
        address: req.body.address,
        postalCode: req.body.postalCode
    },
    include: [ Address ]
}).then(patient => {
    // Check the query generated by this function
    // It should create both the patient and address
});

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

Combining multiple constraints for a single foreign key in SQLite

In SQLite, I have a table with a specified foreign key (FK) like this: CONSTRAINT "model" FOREIGN KEY("category_id") REFERENCES "category"("id") deferrable initially deferred and I want to add ON DELETE CASCADE. Si ...

What is the ideal database schema for a social networking platform?

Reader Categories Connection Reader1 Reader2 Date (or any other relevant connection details) Articles A reader's access to an article is limited to those articles within the same connection group as the reader. I am looking for the most efficie ...

Is it redundant to use flatMap in RXJS?

I recently came across an enlightening article on RXJS which delves into the concept of flatMap. After understanding its purpose - to flatten observable of observables into a single observable sequence (similar to SelectMany in C#) - I noticed an interes ...

The GitHub-hosted package encounters a failure during the npm publish process

Last week everything was running smoothly, but now I am encountering an error and not sure what went wrong. (Apologies for the formatting as there are many lines of log) Running Node version: v10.15.3 Using npm version: 6.4.1 After executing npm publish ...

Angular is showing an error indicating that the property "name" is not found on an empty object

After thorough checking, I have confirmed that the property does exist with the correct key. However, it is returning an error message stating name is not a property of {}. I attempted to assign this object to an interface along with its properties but enc ...

Creating multiple "read more" and "read less" buttons on a single webpage

Can you figure out what's going wrong here? I assigned each one a separate ID, but it's still not functioning properly in my code. I need to get this fixed for an assignment that's due in a few days, so any help is appreciated! function r ...

Updating Vue-Devtools props in Chrome while executing asynchronous promise functions: A step-by-step guide

When working with Vue 3 and mutating a prop that is an object (I understand it's not recommended to mutate props directly, but in this case it works because it's passed by reference as an object), I noticed that the changes reflect in the Vue Dev ...

Error: Unable to initialize monthSelectPlugin as a constructor while trying to utilize the Flatpickr plugin

I'm trying to incorporate the monthSelectPlugin for flatpickr in a Rails application. I have it specified in my importmap like this: pin "flatpickr/dist/plugins/monthSelect", to: "https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/emai ...

Breaking on newline, excluding newline-space in JavaScript

I want to divide my string into an array based on new lines, excluding those that start with a space. ORGANIZER;<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3758455056595e4d524577524f565a475b521954585a">[email prot ...

Reduce the length of the text to 50 characters after the current word, while ensuring that the word

Looking for a way to shorten text after reaching 50 characters, making sure not to split words in the middle when cutting off. For example: Contrary to popular belief, Lorem Ipsum is not simply text (59 chars) Desired output: Contrary to popular belief, ...

The light rotation issue in ThreeJS

No matter if I import the scene or create every mesh and light through code, the issue remains the same. My scene consists of a plane, a cube, and a spot light. The spot light is rotated 45 degrees on the y-axis. In the first example, it is positioned at ...

Retrieve information from json, divide it, and transfer it to the chart for display

Greetings everyone! In my project, I am parsing a JSON file from an online API. However, I have encountered a roadblock while trying to split the data. Despite searching extensively on platforms like YouTube, I haven't been able to find a solution tha ...

Discover the magic of triggering events that dynamically alter CSS styles

I am trying to implement an eventBus in the App.vue component that allows me to change a modal's CSS based on a payload object. For example, if I pass { type: 'success' }, the border of the modal should turn green, and if I pass { type: &apo ...

Create a Buffer that includes all the characters of the alphabet when converted to

My current project involves using Node.js to generate secure, random tokens. Here is a snippet of the code I'm using: crypto.randomBytes(32).toString("hex"); // dd89d6ab1a7196e8797c2da0da0208a5d171465a9d8e918d3b138f08af3e1852 Although this method wo ...

Adding several lines of HTML content from an object using jQuery's append method

Currently, this is what I have: $(document).ready(function() { $.ajax({ type:"GET" , url:'{{url("/api/getcart")}}' , dataType:"json", success: function(data){ $('#price').append(data.cartitems[1].product.pr ...

PHP and MySQL collaborate for live countdowns in real-time

Looking for a code solution to implement a real-time countdown feature, similar to deal expiration timers on shopping websites. I have an expiry time stored in MySQL which needs to be displayed whenever the page is accessed. Additionally, it should calcul ...

Generate an asynchronous boolean promise when calling the isPresent function in Protractor

I'm currently working on a function that checks the presence of an element and returns a boolean value accordingly. However, I am facing an issue where the response includes unnecessary information. the output displays: false How can I adjust my cod ...

Creating a concise TypeScript declaration file for an established JavaScript library

I'm interested in utilizing the neat-csv library, however, I have encountered an issue with it not having a typescript definition file available. Various blogs suggest creating a basic definition file as a starting point: declare var neatCsv: any; M ...

Guide to implementing bidirectional data binding for a particular element within a dynamic array with an automatically determined index

Imagine having a JavaScript dynamic array retrieved from a database: customers = [{'id':1, 'name':'John'},{'id':2, 'name':'Tim}, ...] Accompanied by input fields: <input type='text' na ...

Conflict between multiple jQuery files

Currently, I am in the process of creating a test website for an upcoming project. However, I have encountered some issues with jQuery. This is a static HTML5 website that includes a social widget. The problem arises when I remove a particular jQuery lin ...