Utilizing Node.js and Sequelize to add data into a database

For my project, I am utilizing MySQL database and Sequelize Js to manage data. Currently, I have two models set up:

Post code model:

module.exports = function(sequelize, Sequelize) {

var Post_code = sequelize.define('post_code', {

    id: {
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER(11)
    },

    code: {
        type: Sequelize.STRING(16),
        allowNull: false,
        unique: true
    },

    city: {
        type: Sequelize.STRING(45),
        allowNull: false
    }
},{
    freezeTableName: true,
    underscored: true
});

Post_code.associate = function(models) {
    models.post_code.hasMany(models.building);
};

   return Post_code;
}

Building model:

module.exports = function(sequelize, Sequelize) {

var Building = sequelize.define('building', {

    id: {
        autoIncrement: true,
        primaryKey: true,
        allowNull: false,
        type: Sequelize.INTEGER(11)
    },

    name: {
        type: Sequelize.STRING(100),
        allowNull: false
    },

    number: {
        type: Sequelize.INTEGER(11),
        allowNull: false
    },

    address: {
        type: Sequelize.STRING(255),
        allowNull: false
    },

    latitude: {
        type: Sequelize.DECIMAL(9,6),
        allowNull: false
    },

    longitude: {
        type: Sequelize.DECIMAL(9,6),
        allowNull: false
    }
},{
    freezeTableName: true,
    underscored: true
});

Building.associate = function (models) {
    models.building.belongsTo(models.post_code, {
        foreignKey: {
            allowNull: false
        }
    });

    models.building.hasMany(models.flat);
};

    return Building;
};

These models are connected in a one-to-many relationship, meaning that each Post code can have many Buildings associated with it.

https://i.stack.imgur.com/MXJy0.jpg

To add a new building to the database, I need to handle POST requests to this route:

"/post-codes/:post_code_id/buildings"

Although I have access to the post_code_id, I am struggling with correctly associating the post_code model with the building.

I attempted something like this:

models.post_code.findById(req.params.post_code_id)
.then(function(postCode){
    postCode.setBuilding(
        models.building.create({
        }).then(function(building){});  
    );    
});

Unfortunately, I haven't been successful with this approach. Any guidance on how to properly insert these associations would be greatly appreciated.

Answer №1

There's an interesting option when using the create method that you might not have heard about yet. Here's a different approach you can try:

db.post_code.find({
  where: {
    id: req.params.post_code_id
  }
}).then(post_code => {
  if (!post_code) {
    return res.status(404).send({
      message: 'No post_code with that identifier has been found'
    });
  } else {
    //create your building logic here
  }
}).catch(err => {
  return res.jsonp(err)
});

This may not be the most conventional way to handle it, but it does double-check if the post_code exists before proceeding.

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 advisable to incorporate await within Promise.all?

Currently, I am developing express middleware to conduct two asynchronous calls to the database in order to verify whether a username or email is already being used. The functions return promises without a catch block as I aim to keep the database logic se ...

Error message: NodeJS express unknown function or method get()

Currently, I am facing an issue while working with express and Pug (Jade) to render a page as the get() function is returning as undefined along with warnings... I followed these steps: npm install express --save npm install pug --save Here's a sn ...

Platform error: Responses not specified for DIALOGFLOW_CONSOLE

I've been struggling with this issue for almost a day now and I'm at a loss for what else to try. For some reason, Dialogflow Fulfillment in Dialogflow ES is refusing to make any HTTP calls. Every time I attempt, I receive the same error message ...

What is the best way to retrieve information from Mongoose in an Express application?

I'm currently working on retrieving data from Mongoose using Express. Specifically, I've set up a username and password form for users to log into my site. The authentication process is supposed to verify the credentials against those stored in t ...

Dealing with unhandled exceptions while passing promises into pg-promise batch transactions

Currently, I am diving into the realm of learning express and pg promise. However, during this journey, I have encountered a puzzling issue that I suspect stems from my somewhat shaky understanding of promises. Essentially, I have crafted some functions f ...

Errors related to TypeScript syntax have been detected within the node_modules/discord.js/typings/index.d.ts file for Discord.JS

I keep encountering typescript syntax errors after pulling from my git repository, updating all npm modules on the server, and running the start script. The errors persist even when using npm run dev or npx tsc. I've attempted the following troublesh ...

How can I implement a popup overlay on a redirected URL in Next.js?

Currently in the process of developing my own URL shortener, I'm looking to incorporate a Call To Action on the target URLs page. My tech stack includes NextJs, Tailwind, NodeJs, and Express. Something along these lines: example image If anyone has ...

Ending the connection to the mongodb database

I am using the native MongoDB driver with ExpressJS and I want to optimize my code by minimizing the opening and closing of connections in my routes. My goal is to open a connection once, use that same connection in all subsequent functions triggered by ne ...

The command line utility for webpack encountered an unfamiliar argument: --output

Here are my npm and node.js versions: https://i.stack.imgur.com/BOkSi.png Whenever I attempt to run the npm dev command: https://i.stack.imgur.com/ozlKy.png The log file shows: 0 info it worked if it ends with ok 1 verbose cli [ '/usr/local/bin/no ...

What is the process for including additional information in a JSON file?

I've been searching for a while now and couldn't find the right solution, so I'm posting my issue here. I am trying to add some data (an object) to a .json file, but each time I add more data, it ends up getting messed up. Here's the co ...

What steps can I take to resolve the "SyntaxError: Unexpected token '?' " issue when trying to connect MongoDB with Node.js?

I am currently utilizing mongodb in conjunction with nodejs. I have set up the server and established the connection to the database. However, I am encountering an issue. Server.js file const http = require('http'); require("./config/dbCon ...

How come running `npm install <folder>` results in installing different dependencies compared to `npm install lib`?

My current project, project1, relies on <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5221262b3e37367f313d3f223d3c373c262112667c6">[email protected]</a>. When attempting to integrate project2 into project1 as a ...

Installing Keyrock Idm onto a Kubernetes clusterDeploying Keyrock Identity

Currently, my Kubernetes Cluster consists of 2 pods - one for MySQL and one for IDM. The cluster itself is running on VirtualBox with 1 master node and 1 worker node. While Keyrock successfully creates the IDM database, there seems to be an issue with mig ...

Comparing NemoJs and NightWatchJS: The Pros and Cons

As a beginner in both frameworks, it appears that Nightwatch has more extensive documentation and API features compared to Nemo. What are the main benefits of choosing one over the other? ...

When attempting to utilize 'express' in the main thread of Electron, I encounter an error stating the module cannot be

I am encountering an issue while using the express library in my main.js file. It functions properly during development build, but when I package the application, I receive the following error: Error: Cannot find module 'express' I am uncerta ...

Can I safely rely on url.parse to verify that redirectURL is limited to the domain?

I am looking to create secure redirects exclusively within the domain example.local. Valid examples include: http://blog.example.local, http://www.example.local/dashboard; whereas invalid examples are: http://blog.example.local, http://blog.example.local.f ...

Using the combination of Node.js, ZeroMQ, and Socket.io, we can implement scoping per

I am currently in the process of developing a web application using node.js and express to deliver a real-time aprs stream to each user through ZeroMQ and socket.io. The idea behind it is that the node.js app receives the complete aprs stream by subscribi ...

Error encountered during the building of a Java project using Gradle

I ran into an issue with Git Bash error output (build failed). Despite attempting to resolve it by installing Python as suggested, setting the Python environment variable in IntelliJ, and following other recommendations, I still encounter the same build ...

Troubleshooting React's failure to start with node.js running behind an Nginx Reverse Proxy

This is my first attempt at setting up a Node.js server in production (other than one Meteor server), and I've run into a problem that I can't figure out on my own. I have built an application using React. Here is the server code: // Imports va ...

Tell me about node-persist

During my online learning journey of Node.js on Udemy, I encountered the term node-persist. Despite searching for it on Google, I couldn't find a clear explanation. Could someone please provide a concise definition of what node-persist is? ...