Sequelize Unique Constraint Across Two Tables - postgresql

I have three tables: survey, survey_owners (join table), users. Surveys naturally have titles and are owned by users. A user can own multiple surveys and a survey can be owned by multiple users (many-to-many relationship).
I have the unique constraint setup on the survey_owners table so there are no duplicates, but now need to figure out how to enforce a unique constraint to address the following: A user should not be able to own multiple surveys with the same title.
That being said, a unique constraint CANNOT be placed on the 'title' column of the survey table because the uniqueness should be only be applied if a user already owns a survey with an identical name.
Any ideas how to implement this in the Sequelize migration and/or model(s)?
Current migration file for survey_owners
'use strict';
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.createTable('survey_owners', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
surveys_id: {
type: Sequelize.INTEGER,
onDelete: 'CASCADE',
references: {
model: 'surveys',
key: 'id'
}
},
users_id: {
type: Sequelize.INTEGER,
references: {
model: 'users',
key: 'id'
}
},
createdAt: {
allowNull: false,
type: Sequelize.DATE,
field: "created_at"
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE,
field: "updated_at"
}
})
.then(() => {
return queryInterface.addConstraint('survey_owners', ['surveys_id', 'users_id'], {
type: 'unique',
name: 'survey_owners'
});
});
},
down: (queryInterface, Sequelize) => {
return queryInterface.dropTable('survey_owners');
}
};

Unfortunately I could not find a way inside Sequelize to handle this constraint so I am handling the logic on the submit action and checking in a JS method. Not the best way but had to move on and this is working.

Related

hasMany foreignKey not working in Sequelize

I have some models - kanban_cards, kanban_checklists, kanban_checkitems.
kanban_cards model:
export default (sequelize, DataTypes) => {
return sequelize.define('kanban_card', {
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.STRING,
allowNull: false
},
label: {
type: DataTypes.STRING,
allowNull: true,
},
listId: {
type: DataTypes.UUID,
allowNull: false
},
...
})
}
kanban_checklist:
export default (sequelize, DataTypes) => {
return sequelize.define('kanban_checklist', {
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.STRING,
allowNull: false
},
cardId: {
type: DataTypes.UUID,
allowNull: false,
}
})
}
And the association is:
const models = {
KanbanCards: KanbanCards(sequelize, Sequelize.DataTypes),
KanbanChecklists: KanbanChecklists(sequelize, Sequelize.DataTypes),
...
}
...
models.KanbanCards.hasMany(models.KanbanChecklists, { as: 'checklists', foreignKey: 'cardId' })
models.KanbanChecklists.belongsTo(models.KanbanCards)
It works fine if I use findAll, but if I try to create, it doesn't work.
It says.
column "kanbanCardId" of relation "kanban_checklists" does not exist
I am going to use cardId rather than kanbanCardId.
I tried to set references to cardId, but it didn't work either.
If you indicated an explicit foreign key column in hasMany you should do the same for the other part - belongsTo:
models.KanbanChecklists.belongsTo(models.KanbanCards, { foreignKey: 'cardId' })
Otherwise Sequelize generate a foreign key name itself like in your case kanbanCard+id:
The name of the foreign key in the join table (representing the target model) or an object representing the type definition for the other column (see Sequelize.define for syntax). When using an object, you can add a name property to set the name of the column. Defaults to the name of target + primary key of target

Sequelize delete instance with n:m and 1:m associations and update Model

I have 2 models in my postgresql db and using sequelize and node:
Users
Transactions
and are associated like this:
UserModel.hasMany(TransactionModel, { as: 'sentTransactions', foreignKey: 'senderId' });
UserModel.hasMany(TransactionModel, { as: 'receivedTransactions', foreignKey: 'receiverId' });
UserModel.belongsToMany(TransactionModel, { as: 'transactionLikes', through: 'UserLike', foreignKey: 'userId' });
TransactionModel.belongsTo(UserModel, { as: 'receiver' });
TransactionModel.belongsTo(UserModel, { as: 'sender' });
TransactionModel.belongsToMany(UserModel, { as: 'likers', through: 'UserLike', foreignKey: 'transactionId' });
Which means a user has many received and sent transactions and each user can "like" many transactions.
How can I delete a transaction and remove all associations (receiver, sender, liker)? I don't want to delete the users too.
I would also like to update the User Model which is defined like this, in order to add an "email" property:
const UserModel = db.define('user', {
id: { type: Sequelize.STRING, unique: true, primaryKey: true },
firstName: { type: Sequelize.STRING },
lastName: { type: Sequelize.STRING },
username: {
type: Sequelize.STRING,
unique: {
args: true,
msg: USERNAME_IS_TAKEN,
},
}
How can I update the model? What will happen to the existing instances?
Thank you in advance for your help!
According to this tutorial your M:N relation should work as you expect it out of the box:
For n:m, the default for both is CASCADE. This means, that if you delete or update a row from one side of an n:m association, all the rows in the join table referencing that row will also be deleted or updated.
Further more, to enforce the CASCADE behavior you may also pass onDelete option to the association calls. Something like this should do the trick:
TransactionModel.belongsToMany(UserModel, { as: 'likers', through: 'UserLike', foreignKey: 'transactionId', onDelete: 'CASCADE' });
Adding an email property to the User Model should be as easy as that:
const UserModel = db.define('user', {
id: {
type: Sequelize.STRING,
unique: true,
primaryKey: true
},
firstName: { type: Sequelize.STRING },
lastName: { type: Sequelize.STRING },
username: {
type: Sequelize.STRING,
unique: {
args: true,
msg: USERNAME_IS_TAKEN,
}
},
email: { type: Sequelize.STRING }
});

How do I set the foreignKey column when bulk creating instances of a model with Sequelize?

I have a one to many relationship between my Polls model and Options model, where one Poll can have multiple options.
The association is set so that Options has a pollId column, which needs to have the correct id from the poll model inserted.
var Options = sequelize.define('Options', {
name: {
type: DataTypes.STRING,
allowNull: false
},
votes: {
type: DataTypes.INTEGER,
allowNull: false
}
}, {
classMethods: {
associate: function(models) {
// associations can be defined here
Options.belongsTo(models.Polls, {
foreignKey: 'pollId',
onDelete: 'CASCADE'
});
}
}
});
I am using bulk create to create multiple options at once, like so
models.Users.findOne({
where: {uuid: user_id}
}).then((user) => {
models.Polls.create({
createdBy: user.get('name'),
userId: user_id,
voter_ids: []
}).then((poll) => {
models.Options.bulkCreate({
})
})
});
Not sure how to add the pollId option to each entry to reflect the same poll model instance, in a way that makes sense.
If you want to use bulkCreate() you have to manually add the pollId to the options. Which you could easily do: {pollId: poll.id}
But theres an even better option:
You can issue a single create() including the poll and the options. Simply add the options to the poll and specify that you want to create these too using the include option of create() See: http://docs.sequelizejs.com/manual/tutorial/associations.html#creating-elements-of-a-hasmany-or-belongstomany-association
models.Polls.create({
createdBy: user.get('name'),
userId: user_id,
voter_ids: [],
options: [
{your first option},
{another option}
]
}, {
include: [ models.Options ]
}
)

How to filter a query based on collection from many-to-many

I have two model objects. Doctors and Hospitals. The model definitions look like:
module.exports = {
schema: true,
autoUpdatedAt: true,
autoCreatedAt: true,
attributes: {
name: {
type: 'string',
required: true,
unique: true
},
hospitals: {
collection: 'hospital',
via: 'doctors',
dominant: true,
},
}
};
and
module.exports = {
schema: true,
autoUpdatedAt: true,
autoCreatedAt: true,
attributes: {
name: {
type: 'string',
required: true,
unique: true
},
doctors: {
collection: 'doctor',
via: 'hospitals',
},
}
};
How can I query doctors that are mapped to certain hospitals? I read a couple posts about through keyword, but I wasn't able to get records to persist to the through/join table. Seems like if I could query the automatic join table, I could get it to work, but I'm curious if there is an "official" way to accomplish this type of query.
My current query looks like: Doctor.find().where({'hospitals': ['548303dcf49435ec4a01f2a2','548303cbf49435ec4a01f2a0']}).populate('hospitals').exec(function (err, doctors) { ... });
The underlying db is mongo, if that matters.
I did cheat a bit but things seem to be working. That said, I am interested if there's a better way to accomplish this type of query.
I created a model object that maps to the auto created join table. So in this case, my additional model object looks like:
module.exports = {
schema: true,
autoUpdatedAt: true,
autoCreatedAt: true,
tableName: 'doctor_hospitals__hospital_doctors',
attributes: {
doctor: {
model: 'doctor',
columnName: 'doctor_hospitals'
},
hospital: {
model: 'hospital',
columnName: 'hospital_doctors'
}
}
};
Now, I query the join table directly and use the results for a sub query:
DoctorHospital.find().where({'hospital': ['548303dcf49435ec4a01f2a2','548303cbf49435ec4a01f2a0']}).exec(function(err, doctorHospitals) {
if(err) return next(err);
Doctor.find().where({'id': _.pluck(doctorHospitals, 'doctor')}).populate('hospitals').exec(function (err, doctors){
if(err) return next(err);
return res.view({
doctors: doctors
});
});
});

sails.js join tables on mongodb native id

I have two collections in mongodb database and model for each of them
App Model
module.exports = {
tableName: 'app',
attributes: {
_id : {
primaryKey: true,
unique: true,
type: 'string',
},
userId: {
model: 'user'
},
title: {
type: 'string',
required: true,
unique: true,
},
createdDate : 'string'
},
};
and User Model
module.exports = {
tableName: 'user',
attributes: {
id : {
primaryKey: true,
unique: true,
type: 'string',
collection: "app",
via : "userId"
},
password: {
type: 'string',
required: true
},
apps : {
collection: "app",
via : "userId"
}
},
};
When i use numeric values for join this collection, it works fine, but when i try do it with mongodb native id object, i get the empty result
How i call join query
User.find().populate('apps').exec(function(err, result) {});
You need to get rid of both the _id and id attribute definitions in your models. Waterline will handle the primary key fields for you automatically (normalizing them to id), so unless you need to change the field type, they can be safely left out. Also, I'm not sure what your intention was by adding collection and via to the id definition, but the primary key is never going to be an association.
Otherwise, your models look correct. If you get rid of those two attributes, things should work fine.