Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize exclude belongs-to-many mapping object

Tags:

sequelize.js

Is there a way when making a SequelizeJS query on an object, and including a relation which has a belongs-to-many association, to have the included property not return the association mapping object with the result?

i.e.:

Users.findAll({include: [{model: Role, as: 'roles'}]})

//yields objects of the following form
user: {
    username: 'test',
    roles: [
        {
           name: 'user',
           UserRoles: {userId: 1, roleId: 1} //<--I do not want this
        }
    ]        
}
like image 556
weagle08 Avatar asked Jul 13 '17 02:07

weagle08


People also ask

What is a one to many relationship in Sequelize?

To create a One-To-Many relationship, the hasMany and belongsTo associations are used together; To create a Many-To-Many relationship, two belongsToMany calls are used together.

How do you include two models in Sequelize?

How do you include two models in Sequelize? Your solution, along with using include: {all:true} in my findAll query, did the trick. instead of using include: {all:true} in findAll you can use include: {model: models. User, as: 'createdByUser'} , etc.

How do you do a right JOIN in Sequelize?

findAll({ include: [{ model: Post, where: { status: { [Op.ne]: 'draft' } }, required: false right: true // will create a right join }] }); Sequelize automatically sets the “required” option to “true”.


2 Answers

Found a solution to this in a github comment: https://github.com/sequelize/sequelize/issues/4074#issuecomment-153054311

gist:

Users.findAll({
    include: [
        {
            model: Role, 
            as: 'roles',
            through: {attributes: []} //<-- this line will prevent mapping object from being added
        }
    ]
});
like image 97
weagle08 Avatar answered Oct 15 '22 06:10

weagle08


You can try specifying the attributes property.

So to include fields say a,b,c you add

attributes: ['a', 'b','c']

To exclude them

attributes:{exclude:['a', 'b','c']}

So findAll looks like

Model.someModel.findAll({
  where: // some condition
  include: // some other model
  attributes: // some fields
})

You can also specify attributes within the include clause

like image 25
Shivam Avatar answered Oct 15 '22 08:10

Shivam