I'm working on a web site where users can have a project, and for each project they have, they are assigned a certain role. Here is the schema
How I can make it with the model of squelize (Or maybe it's better to don't use an ORM (it's what I'm thinking right now..))
Here you can see a part of my model :
//Users
module.exports = function(sequelize, DataTypes) {
return sequelize.define('User', {
id: {
type: DataTypes.INTEGER(11),
allowNull: false,
primaryKey: true,
autoIncrement: true
},
// ******** //
}, {
tableName: 'users',
freezeTableName: true
});
};
//Projects
module.exports = function(sequelize, DataTypes) {
return sequelize.define('Project', {
id: {
type: DataTypes.INTEGER(11),
allowNull: false,
primaryKey: true,
autoIncrement: true
},
name: {
type: DataTypes.STRING,
allowNull: true
}
}, {
tableName: 'projects',
freezeTableName: true
});
};
//ProjectRole :
module.exports = function(sequelize, DataTypes) {
return sequelize.define('ProjectRole', {
id: {
type: DataTypes.INTEGER(11),
allowNull: false,
primaryKey: true,
autoIncrement: true
},
name: {
type: DataTypes.STRING,
allowNull: true
}
}, {
tableName: 'projects_roles',
freezeTableName: true
});
};
//user has projects :
module.exports = function(sequelize, DataTypes) {
return sequelize.define('UserProject', {
id: {
type: DataTypes.INTEGER(11),
allowNull: false,
primaryKey: true,
autoIncrement: true
},
}, {
tableName: 'users_has_projects',
freezeTableName: true
});
};
Related
While trying to save data into postgres database using sequelize BlogModel.create() system failed to save the data into table and server is returning columns createdat, updatedat, multiple times in console. ( please see below ). In the scheme I have added the column only once, can someone advise on this issue here ?
Executing (default): INSERT INTO "userBlogs" ("id","email","blogdetails","tags","createdat","updatedat","createdAt","updatedAt") VALUES (DEFAULT,$1,$2,$3,$4,$5,$6,$7) RETURNING "id","email","blogdetails","tags","createdat","updatedat","createdAt","updatedAt";
//userBlogs.js
'use strict';
module.exports = (sequelize, DataTypes) => {
const userBlogs = sequelize.define('userBlogs', {
id: {
type: DataTypes.INTEGER(10),
allowNull: false,
primaryKey: true,
autoIncrement: true
},
email: {
type: DataTypes.STRING(255),
allowNull: false
},
blogdetails: {
type: DataTypes.TEXT,
allowNull: false
},
tags: {
type: DataTypes.STRING(255),
allowNull: false
},
createdat: {
type: DataTypes.DATE,
allowNull: false,
defaultValue: DataTypes.NOW
},
updatedat: {
type: DataTypes.DATE,
allowNull: false,
defaultValue: DataTypes.NOW
}
}, {
timestamps: true,
tableName: 'userBlogs'
});
return userBlogs;
};
//server.js
const usersBlogSchema = require('./modals/userBlogs');
const BlogModel = usersBlogSchema(sequelize, DataTypes);
app.post('/service/createblogs', async (req, res, next)=> {
try {
const userEmail = req.body.email;
const blogDetails = req.body.blogValue;
const tags = req.body.tagValue;
if (Object.keys(req.body).length === 0) {
res.status(403).json({ fail: "Invalid blog request or blog request is blank !" });
} else {
var requestData = {email:userEmail, blogdetails:blogDetails, tags:tags };
const createBlogRequest = await BlogModel.create(requestData);
res.status(200).json({ success: true });
}
} catch (e) {
console.log(e)
return next(e);
}
});
Returning createdAt and updatedAt multiple times because you have added columns (createdAt and updatedAt )and also timestamps:true ,
timestamps also adds these both columns
use either columns or timestamps
'use strict';
module.exports = (sequelize, DataTypes) => {
const userBlogs = sequelize.define('userBlogs', {
id: {
type: DataTypes.INTEGER(10),
allowNull: false,
primaryKey: true,
autoIncrement: true
},
email: {
type: DataTypes.STRING(255),
allowNull: false
},
blogdetails: {
type: DataTypes.TEXT,
allowNull: false
},
tags: {
type: DataTypes.STRING(255),
allowNull: false
},
}, {
timestamps: true,
tableName: 'userBlogs'
});
return userBlogs;
};
I have a MySql DB and using sequelize.
I have a recipe and ingredients tables.
I want to pass the ingredients as an array to the api.
So I researched and discovered I can use get/set to achieve this.
But I get an "Unknown coumn 'ingredients' in 'field list'".
This is my model. The line
console.info("getDataValue...", this);
never gets executed.
function model(sequelize) {
const attributes = {
recipeTitle: { type: DataTypes.STRING(255), allowNull: false },
category: { type: DataTypes.STRING(30), allowNull: false },
recipeSource: { type: DataTypes.STRING(100), allowNull: false },
recipeSourceData: { type: DataTypes.TEXT(), allowNull: true },
method: { type: DataTypes.TEXT(), allowNull: true },
comments: { type: DataTypes.TEXT(), allowNull: true },
prepTime: { type: DataTypes.STRING(10), allowNull: true },
cookTime: { type: DataTypes.STRING(10), allowNull: true },
rating: { type: DataTypes.FLOAT, allowNull: false },
owner_id: { type: DataTypes.INTEGER, allowNull: false },
ingredients: {
type: DataTypes.TEXT,
get() {
console.info("getDataValue...", this);
return JSON.parse(this.getDataValue("ingredients"));
},
set(val) {
if (!Array.isArray(val)) {
throw new Error("ingredients must to be an array");
}
this.setDataValue("ingredients", JSON.stringify(val));
},
},
};
This is my validate-request middle ware and it does have the ingredients
when i console.info("valreq...").
So it seems its the schema.validate that fails??
function validateRequest(req, next, schema) {
console.info("valreq...", req.body);
const options = {
abortEarly: false, // include all errors
allowUnknown: true, // ignore unknown props
stripUnknown: true, // remove unknown props
};
const { error, value } = schema.validate(req.body, options);
if (error) {
next(`Validation error: ${error.details.map((x) => x.message).join(", ")}`);
} else {
console.info("value...", value);
req.body = value;
next();
}
}
SCHEMA
Below is my schema structure, kindly correct me if I am getting it wrong. I want to be able to update the ConnectState from false to true using an ObjectId
phones: {
type: String,
required: true,
},
User: {
type: mongoose.Schema.Types.ObjectId,
ref: "user",
// required: true,
},
Userpost: {
type: mongoose.Schema.Types.ObjectId,
ref: "userpost",
// required: true,
},
friendshipStatus: [
{
isFriend: {
FProfile: {
type: mongoose.Schema.Types.ObjectId,
ref: "profile",
},
ConnectStatus: {
type: Boolean,
default: false,
},
},
},
],
});
What I have tried
I want to update the Boolean value on ConnectStatus from false to true. I know I am getting the process wrong.
const result = await Profile.updateOne(
{ "friendshipStatus.isFriend.FProfile": uid },
{ $set: { "friendshipStatus.$.isFriend.ConnectStatus": true } },
{ arrayFilters: [{ "friendshipStatus.isFriend.FProfile": uid }] }
);
Try with:
const result = await Profile.update(
{ 'friendshipStatus.isFriend.FProfile': uid },
{ $set: { 'friendshipStatus.$.isFriend.ConnectStatus': true } },
);
i am using PostgreSQL with Sequelize ORM to create my db.
I have this models:
models.js
const Users = db.define("users", {
name: {
type: DataTypes.STRING,
},
lastname: {
type: DataTypes.STRING,
},
sector: {
type: DataTypes.STRING,
},
email: { type: DataTypes.STRING, unique: true, allowNull: false },
password: { type: DataTypes.STRING, allowNull: false },
points: { type: DataTypes.INTEGER, defaultValue: 0 },
suscripcion: { type: DataTypes.BOOLEAN, defaultValue: false },
preference_id: { type: DataTypes.STRING },
});
const Pronostico = db.define("pronosticos", {
matchId: {
type: DataTypes.STRING,
unique: true,
},
winner: {
type: DataTypes.STRING,
},
goalHome: {
type: DataTypes.INTEGER,
},
goalAway: {
type: DataTypes.INTEGER,
},
});
//REFRESH TOKEN
const RefreshToken = db.define("refreshTokens", {
token: {
type: DataTypes.STRING,
},
expiryDate: {
type: DataTypes.DATE,
},
userId: {
type: DataTypes.STRING,
},
});
RefreshToken.createToken = async function (user) {
let expiredAt = new Date();
expiredAt.setSeconds(expiredAt.getSeconds() + config.jwtRefreshExpiration);
let _token = uuidv4();
let refreshToken = await this.create({
token: _token,
userId: user.id,
expiryDate: expiredAt.getTime(),
});
return refreshToken.token;
};
RefreshToken.verifyExpiration = (token) => {
return token.expiryDate.getTime() < new Date().getTime();
};
This are the Relationships:
Users.hasMany(Pronostico, { as: "pronosticos" });
Pronostico.belongsTo(Users, { foreignKey: "userId", as: "user" });
RefreshToken.belongsTo(User, {
foreignKey: 'userId', targetKey: 'id'
});
User.hasOne(RefreshToken, {
foreignKey: 'userId', targetKey: 'id'
});
Somewhere on my server, I have this controller which creates a refreshToken:
let refreshToken = await RefreshToken.createToken(user);
The problem is that I get an error that says "column userId doesnt exist in refreshTokens relationship.
Maybe I have some issues with the relationships but I think they are OK.
Any suggestion?
I'm new to sequelize as a user and I use the 'many to many' option in the team situation. I created my code but : user_team is not associated to team! i am getting error how can i fix it. I'm doing it for a task, I would be very happy if you help me.tanks
If the structure is also wrong, can you tell me what my mistakes are?
userteam.js
module.exports = (sequelize, DataTypes) => {
const UserTeam = sequelize.define(
"user_team",
{
user_team_id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
},
user_id: {
type: DataTypes.INTEGER,
primaryKey: false,
references: {
model: "user",
key: "user_id",
},
onDelete: "cascade",
onUpdate: "cascade",
unique: "unique-team-per-user",
},
team_id: {
type: DataTypes.INTEGER,
primaryKey: false,
references: {
model: "team",
key: "team_id",
},
onDelete: "cascade",
onUpdate: "cascade",
unique: "unique-team-per-user",
},
},
{ timestamps: false, tableName: "user_team", underscored: true }
);
UserTeam.associate = (models) => {
UserTeam.belongsTo(models.User, {
foreignKey: "user_id",
targetKey: "user_id",
as: "User",
});
UserTeam.belongsTo(models.Team, {
foreignKey: "team_id",
targetKey: "team_id",
as: "Team",
});
};
return UserTeam;
};
user.js
module.exports = (sequelize, DataTypes) => {
const User = sequelize.define(
"user",
{
user_id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
},
firstName: {
type: DataTypes.STRING,
allowNull: false,
},
lastName: {
type: DataTypes.STRING,
allowNull: false,
},
password: {
type: DataTypes.STRING,
allowNull: false,
},
email: {
type: DataTypes.STRING,
allowNull: false,
},
},
{ timestamps: true, tableName: "user", underscored: true }
);
User.associate = (models) => {
User.hasMany(models.Todo, {
as: "todos",
foreignKey: "userId",
});
User.hasMany(models.Team, {
as: "teams",
foreignKey: "admin",
});
User.belongsToMany(models.Team, {
as: "TeamsForUser",
through: models.UserTeam,
foreignKey: "user_id",
});
};
return User;
};
team.js
module.exports = (sequelize, DataTypes) => {
const Team = sequelize.define(
"team",
{
team_id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
},
teamName: {
type: DataTypes.STRING,
allowNull: false,
},
admin: {
type: DataTypes.INTEGER,
allowNull: false,
},
},
{ tableName: "team", underscored: true }
);
Team.associate = (models) => {
Team.belongsTo(models.User, {
as: "user",
foreignKey: "admin",
});
Team.belongsToMany(models.User, {
as: "UserInTeam",
through: models.UserTeam,
foreignKey: "team_id",
});
};
return Team;
};
controller.js
const getAll = async (req, res, next) => {
try {
const myTeams = await Team.findAll({
include: [{ model: UserTeam }],
});
myTeams.forEach((element) => {
console.log(element.get());
});
return res.status(200).json(myTeams);
} catch (err) {
console.log(err.message);
res.status(500).json({ message: err });
}
};
i solved this problem
just add to index database config js
db.users.belongsToMany(db.team, {
as: "teams",
through: "user_team",
foreignKey: "user_id",
});
db.team.belongsToMany(db.users, {
as: "users",
through: "user_team",
foreignKey: "team_id",
});
enter code here