user944513
user944513

Reputation: 12729

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

Upvotes: 4

Views: 5791

Answers (2)

piotrbienias
piotrbienias

Reputation: 7401

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)
    })

Upvotes: 6

No One
No One

Reputation: 119

Use delete key

    var YourJson = [{
    "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
        }
      }
    ]
  }];

    delete YourJson['0']['Projects']['0']['user_project'];

    console.log(YourJson)

Upvotes: 0

Related Questions