Sunday, 12 March 2017

Sequilize.js - Association, 2 tables

Technologies used: Node.js, Express.js, Sequilize.js

I'm trying to connect two tables. There is a user table and a color table.

A color belongs to a user, and a user can have one color.

My file structure:

My Project
|__config
   |__db.js
|__models
  |__user.js
  |__color.js
|__routes
  |__index.js
|__app.js

In my user.js file:

module.exports = function(sequelize, DataTypes) {
    return sequelize.define('user', {
        /* attributes, such as: username */
    });
};

In my color.js file:

module.exports = function(sequelize, DataTypes) {
    return sequelize.define('color', {
        color: {
            type: DataTypes.STRING,
            allowNull: false
        }
    });
};

Then in db.js this is where I configure these files:

const db = {};

db.sequelize = sequelize;
db.Sequelize = Sequelize;

db.user = sequelize.import('../models/user.js');
db.color = sequelize.import('../models/color.js');


db.color.belongsTo(db.user);
db.user.hasOne(db.color);

module.exports = db;

Now is where the trouble begins. When someone creates a new user account (using a POST request), they must also select a color. So the user information is going to go into the user table, and the color information will go into the color table... but how do I do this? How do I link these two tables at the create phase. Below is what I have so far.

My POST request is like this in my index.js file:

const express = require('express');
const router = express.Router();
const db = require('../config/db');

router.post('/createNewUser', function(req, res) {
    const username = req.body.username
    const color = req.body.color

    db.user.create({
        username: username
        color: color
    }, {
       include: db.color
   }).then(function(result) {
        //do something
   }).catch(function(err) {
        //in case of error
   });
});

Creating the tables works fine (all that config code is in the app.js file, not included here). The tables get created; the username is put into the user table and the color is placed in the color table, but the userID in the color table is null.



via MonkeyOnARock

No comments:

Post a Comment