首页 > 解决方案 > 如何使用续集从响应中删除属性?

问题描述

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

像这样获取数据

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

得到这样的回应

 [{
    "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
        }
      }
    ]
  }]

预期响应

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

我在我的项目中使用 sequelize(http://docs.sequelizejs.com)。我正在从 .我获取数据DB。我有很多映射我已经添加了attributes属性以删除不必要的数据。但这对我不起作用

标签: javascriptnode.jssequelize.js

解决方案


您可以使用options.include[].through.attributes定义从关系表中选择的字段,因此您可以使用:

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

推荐阅读