This is my ToWatch Model in toWatch-model.js file which in code has UserModel->ToWatch 1:1 relationship and has ToWatch->MovieModel 1:M relationship.
const Sequelize = require('sequelize');
const sequelize = require('./../common/db-config');
const MovieModel = require ("./movie-model");
const UserModel = require("./user-model");
const Model = Sequelize.Model;
class ToWatch extends Model{}
ToWatch.init({
id: {
type: Sequelize.INTEGER,
allowNull: false,
primaryKey: true,
autoIncrement: true,
field: 'id_towatch'
},
date: {
type: Sequelize.DATE,
allowNull: false,
field: 'date'
},
userId: {
type: Sequelize.INTEGER,
allowNull: false,
field: 'id_user',
references:{
model: UserModel,
key: "id"
}
},
movieId: {
type: Sequelize.INTEGER,
allowNull: false,
field: 'movie_id_towatch',
references:{
model: MovieModel,
key: "id"
}
},
},
{
sequelize,
modelName: 'towatch',
tableName: 'towatch',
timestamps: false
// options
});
//Here is the relation ************
UserModel.hasOne(ToWatch, {
foreignKey: {
type:Sequelize.DataTypes.INTEGER,
allowNull:false,
name:'fk_foreign_key_towatch'
}
});
ToWatch.belongsTo(UserModel);
ToWatch.hasMany(MovieModel, {
foreignKey: {
type:Sequelize.DataTypes.INTEGER,
allowNull:false,
name:'movie_id_towatch'
}
});
MovieModel.belongsTo(ToWatch);
module.exports = ToWatch;
I watched many tutorials, but being my first time trying to make a method that will return everything including something from my other table via ID, I wasn't sure where to put and how to put data that I need in this method, considering it has .then(data=>res.send). Tutorials were doing it other ways by fetching or using async-await, and even documentation didn't help me here. Can somebody tell me what to put and where inside this method, that is inside toWatch-controller.js file for me being able to see let's say all the movie data (title,img,date) ,as an array I think, of the getToWatch method.
const ToWatch = require('./../models/toWatch-model');
module.exports.getToWatch = (req,res) => {
ToWatch.findAll().then(toWatch => {
[WHAT DO I PUT HERE?]
res.send(toWatch);
}).catch(err => {
res.send({
status: -1,
error:err
})
})
}
I need something like this ToWatch{
color:red,
cinema:"MoviePlace",
movieId{title:"Anabel", img:"URL", date:1999.02.23}
As I understood your question right, what you trying to do is return toWatch model instances with including User and Movie models.
To do so you can pass options in findAll() method like below:
ToWatch.findAll({include: [{model: User}, {model: Movie}]})... //and rest of your code
Or alternatively to keep your code clean you can use scopes:
// below the toWatch-model.js file
ToWatch.addScope('userIncluded', {include: {model: User}})
ToWatch.addScope('movieIncluded', {include: {model: Movie}})
And in the getToWatch method:
// you can pass several scopes inside scopes method, its usefull when you want to combine query options
ToWatch.scopes('userIncluded', 'movieIncluded').findAll()... //rest of your code
For more information check out sequelize docs
Related
This is my current setup:
const { Model, DataTypes } = require('sequelize');
class CustomModel extends Model {
static init(attributes, config) {
return super.init(attributes, {
...config,
timestamps: true,
underscored: true,
createdAt: 'created_at',
updatedAt: 'updated_at',
});
}
}
class User extends CustomModel {
ahoy() {
const { email } = this.get();
console.log(`Ahoy, ${email}`);
}
}
User.init({
id: {
type: DataTypes.UUID,
primaryKey: true,
allowNull: false,
defaultValue: DataTypes.UUIDV4,
},
email: {
type: DataTypes.STRING,
allowNull: false,
unique: true
},
}, myConfigHere);
I now want to ensure that all User attributes, as well as its model methods, are showing up in VSCode autocomplete. How can I make this happen?
const user = await User.findOne({ where: { email: 'john#example.com' } });
user.email; // No autocomplete while typing
user.ahoy() // No autocomplete while typing
When I change the code to class User extends Model, then I can see the ahoy() being autocompleted, yet this does not apply to .email
Is there a way to fix this (e.g. with JSDoc)?
If you are using pure Javascript you won't be able to do that.
Consider using Typescript, then VSCode (or any editor really) will be able to watch your Object and suggest what attribute you want from it.
I have started learning sequelize.js with node.js and having hard time defining relationships between models. I am trying to create 1:N relationship between users and roles tables i.e. many users can have same role.
Problem
When I query user model to test the defined relation ship it gives me error that original: error: column "RoleId" does not exist.
roles model:
'use strict';
const {
Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
class Role extends Model {
/**
* Helper method for defining associations.
* This method is not a part of Sequelize lifecycle.
* The `models/index` file will call this method automatically.
*/
static associate(models) {
// define association here
Role.hasMany(models.User, {as: 'users'});
}
}
Role.init({
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name:{
type: DataTypes.STRING,
allowNull: false
}
}, {
sequelize,
modelName: 'Role',
tableName: 'roles',
});
return Role;
};
users model:
'use strict';
const {
Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
class User extends Model {
/**
* Helper method for defining associations.
* This method is not a part of Sequelize lifecycle.
* The `models/index` file will call this method automatically.
*/
static associate(models) {
// define association here
// User.belongsTo(models.Role, {foreignKey: 'roleId', as: 'role'});
User.belongsTo(models.Role);
}
}
User.init({
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.STRING,
allowNull: false
},
email: {
type: DataTypes.STRING,
allowNull: false
},
mobile: {
type: DataTypes.STRING,
allowNull: false
}
// },
// roleId: {
// type: DataTypes.STRING,
// allowNull: false
// }
}, {
sequelize,
tableName: 'users',
modelName: 'User',
});
return User;
};
relationship tester js code:
const { User, Role } = require('./models');
User.findOne({
where: {email: 'admin#papertrader.org'}
})
.then((findedUser) => {
console.log(findedUser)
})
.catch((err) => {
console.log("Error while find user : ", err)
});
Can anyone one please guide me what is wrong with my code?
Here is the code below for one of my tables
const { Model, DataTypes } = require('sequelize');
const Algorithm = require('./algorithm');
const Exchange = require('./exchange');
const User = require('./user');
//#JA - This model defines the api keys for each user's exchange
//#JA - For security reasons in case the database gets hacked the keys will be stored using encryption.
module.exports = function(sequelize){
class AlgorithmRule extends Model {}
AlgorithmModel = Algorithm(sequelize);//#JA - Gets a initialized version of Algorithm class
ExchangeModel = Exchange(sequelize);//#JA - Gets initialized version of the Exchange class
UserModel = User(sequelize);//#JA - Gets a initialized version of User class
var AlgorithmRuleFrame = AlgorithmRule.init({
algorithm_id: {
type: DataTypes.INTEGER,
allowNull: false,
references: {
model: AlgorithmModel,
key: 'id',
}
},
exchange_id: {
type: DataTypes.STRING,
references: {
model: ExchangeModel,
key: 'name',
},
},
user_id: {
type: DataTypes.INTEGER,
references: {
model: UserModel,
key: 'id',
},
},
type : { //Partial-Canceled implies that the order was partially filled and then canceled.
type: DataTypes.ENUM('Percent Of Equity','Cash'),
allowNull: false,
defaultValue: 'Percent Of Equity'
},
type_value: { //#JA - This will be either treated as a percentage or 'cash' value for the type chosen for the algorithm.
type: DataTypes.DECIMAL(20,18),
allowNull: false
},
}, {
sequelize,
modelName: 'AlgorithmRule',
indexes: [{ unique: true, fields: ['algorithm_id','exchange_id','user_id'] }]
});
return AlgorithmRuleFrame
};
I'm trying to set this up so that I can allownull:false on algorithm_id and exchange_id and user_id. I want it so there HAS to be values there for any records to be allowed.
I can't even get allowNull:false manually through the database itself. So my first question is, is this even possible?
If it is, how do I do it with sequelize?
I can use the typical hasOne() with foreign key commands because then I can't create a composite unique of the foreign keys. The only way I was able to do this was the way I did using the references: json structure.
How do I allownull:false for a foreignKey reference defined the way I have it?
To be clear something like this will NOT work
Task.belongsTo(User, { foreignKey: { allowNull: false }, onDelete: 'CASCADE' })
This will NOT work because I'm using a composite unique key across 3 foreign keys and in order to do that I need reference to it's name and that is not possible unless it's defined on the table before these commands above our input. Hopefully this makes sense.
Any help is greatly appreciated!
Okay so apparently
algorithm_id: {
type: DataTypes.INTEGER,
allowNull: false,
references: {
model: AlgorithmModel,
key: 'id',
}
},
This code is correct. HOWEVER, if you created the database already and the foreign key was already defined it will NOT change the allowNull via the alter command. You have to COMPLETELY drop the table and THEN it will allow the allowNull:false attribute to work.
This threw me for a loop for a long time, so I help this saves someone else a lot of frustration.
I have the below two models, and am trying to change the userId property on the Report model to not have to be unique. When I change unique to false, or delete the property altogether, I am still getting the unique validation error when trying to create a Report with an existing userId (using models.Report.create({ userId: 1 }) when 1 is an existing user's id). I've also tried making a migration and running that to no avail.
Am I missing something here? Been stuck on this for a while, so any input is massively appreciated. Thank you.
Report.js
module.exports = (sequelize, DataTypes) => {
const Report = sequelize.define(
'Report',
userId: {
allowNull: false,
type: Sequelize.INTEGER,
unique: true,
},
);
Report.associate = function(models) {
Report.belongsTo(models.UserInfo, { foreignKey: 'userId' });
};
return Report;
};
UserInfo.js
module.exports = (sequelize, DataTypes) => {
const UserInfo = sequelize.define(
'UserInfo',
{
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
);
UserInfo.associate = function associate(models) {
ApplicantInfo.hasMany(models.Report, { foreignKey: 'applicantId' });
};
return ApplicantInfo;
};
I have two tables below:
1. Poll
2. Option
The Poll model is as follows:
const Sequelize = require('sequelize');
let dbService = require('../services/dbService.js');
let Option = require('./options');
let Poll = dbService.define('Poll', {
poll: {
type: Sequelize.STRING,
allowNull: false
},
isAnonymous: {
type: Sequelize.STRING,
allowNull: false
},
startDate: {
type: Sequelize.STRING,
},
endDate: {
type: Sequelize.STRING,
},
active: {
type: Sequelize.BOOLEAN,
}
});
Poll.hasMany(Option);
module.exports = Poll;
The Option model is as follows:
const Sequelize = require('sequelize');
let dbService = require('../services/dbService.js');
let Option = dbService.define("option", {
name: Sequelize.STRING
});
module.exports = Option;
This is my /GET route for api/poll/:id
I want to update the poll. All the other routes are working fine. I am just stuck on updating the model.
The controller for /PUT api/poll/:id
The service for /PUT api/poll/:id
This only updates the Poll table, the Option table's column does not get updated. How can I achieve the update with the one to many association like this?
I have tried this too! Sequelize update with association
I have even done the same as the sequelize docs. But I am unable to achieve what I want. I've been stuck on this for a while. Any kinda help will be appreciated.
Thanks!
For update you can try SequelizeModel.upsert() function.