Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove attribute from response using sequelize?

const User = sequelize.define('user', {
    // attributes
    firstName: {
        type: Sequelize.STRING,
        allowNull: false
    },
    lastName: {
        type: Sequelize.STRING
        // allowNull defaults to true
    }
});

const Project = sequelize.define('project', {
    // attributes
    projectName: {
        type: Sequelize.STRING,
        allowNull: false
    }
});
User.belongsToMany(Project,{as:'Projects',through:'user_project'});
Project.belongsToMany(User,{as:'Users',through:'user_project'});

Fetching data like this

app.use('/get', (req, res) => {
    User.findAll({
        attributes: ['firstName'],
        include: [{
         model:Project,
            as:'Projects',
            attributes: ['projectName']
        }]}).then((result) => {
        res.json(result)
    })
})

getting a response like this

 [{
    "firstName": "naveen",
    "Projects": [
      {
        "projectName": "EV",
        "user_project": {
          "createdAt": "2019-07-21T06:17:49.119Z",
          "updatedAt": "2019-07-21T06:17:49.119Z",
          "userId": 1,
          "projectId": 3
        }
      }
    ]
  }]

Expected response

[{
    "firstName": "naveen",
    "Projects": [
      {
        "projectName": "EV",
      }
    ]
  }]

I am using sequelize in my project(http://docs.sequelizejs.com).I am fetching data from DB.I have many to many mapping I already add attributes property to remove unnecessary data. but it not works for me

like image 348
user944513 Avatar asked Sep 19 '25 19:09

user944513


1 Answers

You could use the options.include[].through.attributes to define fields selected from the relation table, so you could use:

User.findAll({
        attributes: ['firstName'],
        include: [{
         model:Project,
            as:'Projects',
            attributes: ['projectName'],
            through: { attributes: [] } // using empty array will cause not to return the relation fields at all
        }]}).then((result) => {
        res.json(result)
    })
like image 155
piotrbienias Avatar answered Sep 22 '25 09:09

piotrbienias