0

I'm new into NodeJS, and I'm experiencing some problems with the relations, models and controllers. I've been reading and trying to understand the Sequelize API, but I don't really know how to perform things, and so I'm stuck.

I'm having 2 main models. One is called Project and the other one is called User. These 2 models, I want to relate them with a third model, called UserProject.

UserProject model references the Project and User models through their PK (project_id, user_id), and also has a third column named "user_type", which will determine whether the user has one rank or another (Master, Developer, ...)

I don't know how to keep going, as I'm getting uncountable errors through the process and it's been 2 days without any light. I'll share my models, controllers and index below:

User Model:

module.exports = (sequelize, Sequelize) => {
const User = sequelize.define("user", {
username: {
  type: Sequelize.STRING
},
password: {
  type: Sequelize.STRING
},
email: {
  type: Sequelize.STRING
}
});

return User;
};

Project Model:

module.exports = (sequelize, Sequelize) => {
const Project = sequelize.define("project", {
title: {
  type: Sequelize.STRING
},
description: {
  type: Sequelize.STRING
},
releaseDate: {
  type: Sequelize.DATE
},
accessCode: {
  type: Sequelize.INTEGER
}
});

return Project;
};

UserProject Model:

const Project = require("./project.model.js");
const User = require("./user.model.js");

module.exports = (sequelize, Sequelize) => {
const UserProject = sequelize.define('userProject', {
userId: {
  type: Sequelize.INTEGER,
},
projectId: {
  type: Sequelize.INTEGER,
},
user_type: {
  type: Sequelize.INTEGER,
}
});

User.belongsToMany(Project, { through: UserProject });
Project.belongsToMany(User, { through: UserProject });

return UserProject;
};

Project Controller:

const db = require("../models");
const Project = db.projects;
const User = db.users;
const Op = db.Sequelize.Op;

// Retrieve all Projects with User from the database.
exports.findAll = (req, res) => {

Project.findAll({ 
include: User
})
.then(data => {
  res.send(data);
})
.catch(err => {
  res.status(500).send({
    message:
      err.message || "Some error occurred while retrieving projects."
  });
});
};

Index.js:

const dbConfig = require("../config/db.config.js");

const Sequelize = require("sequelize");
const sequelize = new Sequelize(dbConfig.DB, dbConfig.USER, dbConfig.PASSWORD, {
host: dbConfig.HOST,
dialect: dbConfig.dialect,
operatorsAliases: false,

pool: {
max: dbConfig.pool.max,
min: dbConfig.pool.min,
acquire: dbConfig.pool.acquire,
idle: dbConfig.pool.idle
}
});

const db = {};

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

db.projects = require("./project.model.js")(sequelize, Sequelize);
db.users = require("./user.model.js")(sequelize, Sequelize);
db.users_projects = require("./userProject.model.js")(sequelize, Sequelize);

module.exports = db;

Can someone tell me what am I missing? Thank you guys

0 Answers0