javascript - 如何使用续集从响应中删除属性?
问题描述
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
属性以删除不必要的数据。但这对我不起作用
解决方案
您可以使用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)
})
推荐阅读
- javascript - 为什么我的 brain.js LSTM 脚本没有从 script 标签中指定的 URL 加载?
- sql - ms-access SQL 链接工作表行顺序保留
- java - 如何通过 Selenium WebDriver (Java API) 在 web 视图中查找 web 元素?
- type-conversion - 将表示列表的字符串转换为 Jython 中的实际列表?
- c++ - 循环展开和 SSE——clang 与 gcc
- javascript - 如果数据库有变化,刷新页面
- node.js - JS加载后获取页面的HTML内容
- c++ - Emacs - ccls:命名空间“std”中没有名为“filesystem”的成员
- julia - 如何在 Julia 中初始化摘要?
- html - Heroku:在应用程序启动时显示自定义页面