Reputation: 12729
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
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
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