I have been trying to build a simple 'messages' app.. After giving MongoDB a try, i found out its really best to do with MySQL.
So but instead of writing all tables / queries etc by hand, I want to learn building it from the ground up with an ORM, a.k. Sequelize.
Lets say I have a user table:
var User = sequelize.define('user', {
email: {
type: Sequelize.STRING,
validate: {
isEmail: true
//msg: "Email is invalid"
}
}
}
And a message table:
var Message = sequelize.define('message', {
message: {type: Sequelize.STRING},
sender: {type: Sequelize.STRING},
read: {type: Sequelize.BOOLEAN}
}
Every user can have many messages, and every message can have 2 users in the conversation.
So when i do this:
User.hasMany(Message);
Message.belongsToMany(User, {through: 'Conversation', foreign_key: 'id'});
User.sync();
Message.sync();
I would expect a 'junction table' named Conversations... Holding the user_id's.. And every message having a reference to the Conversation_id, But apparently its not true...
Does anybody know what the correct way is?
Thanks!
For create Conversations table you need sync all: sequelize.sync();.
Related
I am building a React Nativeapp with MYSQL as the dabase and I am using SequelizeORM on Node.js. The problem is that I have a table called Like and there is a column field called userId and I simply store the ID of the users there. But the userId field gets cleared randomly. Like when I am restarting the database, or when there is an error and I need to restart the database or I am restarting the Android Emulator.
Here is how it looks:
CreateLikeModel.init({
id:{
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true,
allowNull: false,
},
userId:{
type: DataTypes.STRING,
allowNull: true
},
food_Name:{
type: DataTypes.STRING,
allowNull: false
},
food_id:{
type: DataTypes.INTEGER,
allowNull: false
}
},
And this is part of the function that saves the user Id when the user carry's out a like functionality:
const user = await CreateCustomer.findOne({where: {id: req.user.id}});
const likeObj ={
user_Id: user?.dataValues?.id?.toString(),
food_Name: food?.dataValues?.food_Name,
food_id: food.dataValues.id as number
}
//check if this user has liked this food
const checkUser = checkLike.find((single)=> single?.dataValues.userId ==
user.dataValues.id);
if(checkUser){
const getLike = await CreateLikeModel.findOne({where: {food_Name:
food.dataValues.food_Name, userId: user?.dataValues.id}});
await getLike?.destroy();//delete the like from the record if the user already liked;
return res.status(200).json('unliked');
}
await CreateLikeModel.create({...likeObj});
return res.status(200).json('liked');
And I connected to the database like this:
sequelizeDB.sync({alter: true}).then(()=>{
console.log('connected to datatbase')
})
I tried the save the userId as a string because it was a number before. Initially, when I used number, it usually reset the userId values to 0.
It still didn't solve the problem.
This was not happening before when I was using user_name instead of userId. What could be causing the issue? For now, I usually manually input the values back in the database when they get deleted.
Inside of likeObj, which you are using as the creation attributes for your like object, you have your User ID field as snake case user_Id, which in your model, I see it in camelCase userId.
I suspect this is the root of why it isn't populating the data correctly, however keep in mind that .sync({ alter: true }) can be a destructive operation, as state in the Sequelize documentation.
I think I've done enough research on this subject and I've only got a headache.
Here is what I have done and understood: I have restructured my MySQL database so that I will keep my user's data in different tables, I am using foreign keys. Until now I only concluded that foreign keys are only used for consistency and control and they do not automatize or do anything else (for example, to insert data about the same user in two tables I need to use two separate insert statements and the foreign key will not help to make this different or automatic in some way).
Fine. Here is what I want to do: I want to use Sequelize to insert, update and retrieve data altogether from all the related tables at once and I have absolutely no idea on how to do that. For example, if a user registers, I want to be able to insert the data in the table "A" containing some user information and in the same task insert in the table B some other data (like the user's settings in the dedicated table or whatever). Same with retrievals, I want to be able to get an object (or array) with all the related data from different tables fitting in the criteria I want to find by.
Sequelize documentation covers the things in a way that every thing depends on the previous one, and Sequelize is pretty bloated with a lot of stuff I do not need. I do not want to use .sync(). I do not want to use migrations. I have the structure of my database created already and I want Sequelize to attach to it.
Is it possible insert and retrieve several rows related at the same time and getting / using a single Sequelize command / object? How?
Again, by "related data" I mean data "linked" by sharing the same foreign key.
Is it possible insert and retrieve several rows related at the same
time and getting / using a single Sequelize command / object? How?
Yes. What you need is eager loading.
Look at the following example
const User = sequelize.define('user', {
username: Sequelize.STRING,
});
const Address = sequelize.define('add', {
address: Sequelize.STRING,
});
const Designation = sequelize.define('designation', {
designation: Sequelize.STRING,
});
User.hasOne(Address);
User.hasMany(Designation);
sequelize.sync({ force: true })
.then(() => User.create({
username: 'test123',
add: {
address: 'this is dummy address'
},
designations: [
{ designation: 'designation1' },
{ designation: 'designation2' },
],
}, { include: [Address, Designation] }))
.then(user => {
User.findAll({
include: [Address, Designation],
}).then((result) => {
console.log(result);
});
});
In console.log, you will get all the data with all its associated models that you want to include in the query
Is it possible to create a column on a MySQL table using Sequelize that can be initialized when creating a new row, but never updated?
For example, a REST service allows a user to update his profile. He can change any field except his id. I can strip the id from the request on the API route, but that's a little redundant because there are a number of different models that behave similarly. Ideally, I'd like to be able to define a constraint in Sequelize that prevents the id column from being set to anything other than DEFAULT.
Currently, I'm using a setterMethod for the id to manually throw a ValidationError, but this seems hackish, so I was wondering if there's a cleaner way of doing this. Even worse is that this implementation still allows the id to be set when creating a new record, but I don't know a way around this as when Sequelize generates the query it calls setterMethods.id to set the value to DEFAULT.
return sequelize.define('Foo',
{
title: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
validate: {
notEmpty: true
}
}
},
{
setterMethods: {
id: function (value) {
if (!this.isNewRecord) {
throw new sequelize.ValidationError(null, [
new sequelize.ValidationErrorItem('readonly', 'id may not be set', 'id', value)
]);
}
}
}
}
);
Look at this Sequelize plugin:
https://www.npmjs.com/package/sequelize-noupdate-attributes
It adds support for no update and read-only attributes in Sequelize models.
In your specific case, you could configure the attribute with the following flags:
{
title: {
type: DataTypes.STRING,
allowNull: false,
unique : true,
noUpdate : true
}
}
That will allow the initial set of the title attribute if is null, and then prevent any further modifications once is already set.
Disclaimer: I'm the plugin author.
By below reference I understood how map many to many with a relationship table
http://sequelizejs.com/docs/latest/associations#many-to-many
User = sequelize.define('User', { user_name : Sequelize.STRING})
Project = sequelize.define('Project', { project_name : Sequelize.STRING })
UserProjects = sequelize.define('UserProjects', {
status: DataTypes.STRING
})
User.hasMany(Project, { through: UserProjects })
Project.hasMany(User, { through: UserProjects })
But how to query Project 's of a User
I Tried like
User.find({where:{id:1},include,[UserProjects]})
User.find({where:{id:1},include,[Projects]})
User.find({where:{id:1},include,[UserProjects]})
User.find({where:{id:1},include,[Projects]})
But i dont get results
Sequelize created table like below
users(id,name)
projects(id,project_name)
userprojects(id,UserId,ProjectId)
I tried https://github.com/sequelize/sequelize/wiki/API-Reference-Associations#hasmanytarget-options
User.find({where:{id:1}}).success(function(user){
user.getProjects().success(function (projects) {
var p1 = projects[0] // this works fine but 2 queries required. I expect in single find. without getProjects
p1.userprojects.started // Is this project started yet?
})
})
How to get all the projects of a USER ??
You should be able to get all of the properties of the user in two different ways: using includes and getting the projects from a user instance.
Using includes the code you submitted above is almost right. This method will only make one query to the database using the JOIN operation. If you want all of the users with their corresponding projects, try:
User.findAll({include: [Project]})
You can also get the projects directly from a user instance. This will take two queries to the database. The code for this looks like
User.find(1).then(function(user) {
user.getProjects().then(function(projects) {
// do stuff with projects
});
});
Does this work for you?
I've just started to get into the framework of Sails for Node. But it seems like I can't get the unique- requirements to work when adding for example users to the sails-mysql database. I can atm add unlimited number of new users with the same username and email.
From what I have read it should work, I did also try with sails-memory and there this exact code did work. Is it something I have missed out?
module.exports = {
attributes: {
username: {
type: 'string',
required: true,
unique: true
},
firstname: {
type: 'string',
required: true
},
lastname: {
type: 'string',
required: true
},
password: {
type: 'string',
required: true
},
birthdate: {
type: 'date',
required: true
},
email: {
type: 'email',
required: true,
unique: true
},
phonenumber: 'string',
// Create users full name automaticly
fullname: function(){
return this.firstname + ' ' + this.lastname;
}
}
};
As I mentioned above, this does work with the memory-storage. And now I have also tried with mongodb where it does work fins as well.
Got support from Sails.js on twitter: "it uses the db layer- suspect it's an issue with automigrations. Would you try in a new MySQL db?"
This answer did work, a new db and everything was just working :)
Just to add to this, since sails uses auto-migrations, if you initially start the server and your model does not have an attribute as unique, the table is built without the unique (index) switch. If you then change an existing attribute in the model to unique, the table will not be rebuilt the subsequent times you start the server.
One remedy during development is to set migrations in your model to drop like this:
module.exports = {
migrate: 'drop' // drops all your tables and then re-create them Note: You loose underlying.
attributes: {
...
}
};
That way, the db would be rebuilt each time you start the server. This would of course drop any existing data as well.