How to use an include with attributes with sequelize?

node.jsOrmsequelize.jsRelationship

node.js Problem Overview


Any idea how to use an include with attributes (when you need to include only specific fields of the included table) with sequelize?

Currently I have this (but it doesn't work as expected):

var attributes = ['id', 'name', 'bar.version', ['bar.last_modified', 'changed']];
foo.findAll({
    where      : where,
    attributes : attributes,
    include    : [bar]
}).success(function (result) { ...

node.js Solutions


Solution 1 - node.js

Something like this should work

foo.findAll({
    where      : where,
    attributes : attributes,
    include    : [{ model: bar, attributes: attributes}]
}).success(function (result) {

Solution 2 - node.js

We can do something like that for exclude or include specific attribute with sequelize in Node.js.

Payment.findAll({
    where: {
        DairyId: req.query.dairyid
    },
    attributes: {
        exclude: ['createdAt', 'updatedAt']
    },
    include: {
        model: Customer,
        attributes:['customerName', 'phoneNumber']
    }
})

Solution 3 - node.js

Course.findAll({where: {
         status:responseCode.STATUS_ACTIVE
     }, attributes:['id','course_title','course_slug','age_group','image','class_duration','no_of_classes','is_course_upcoming'],
     order:[['is_sorting','ASC']],
    include:{model:Section,attributes:['id','title','course_id','start_date','end_date']},
}).then(course_detail =>{
    result(null,course_detail);
}).catch(err =>{
    console.log(err)
});

Solution 4 - node.js

Use the select without hyphen (-) only blank spaces like this.

Model.find().select('attr1 attr2 attr3')

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionborisdiakurView Question on Stackoverflow
Solution 1 - node.jsJan Aagaard MeierView Answer on Stackoverflow
Solution 2 - node.jsSanket VananiView Answer on Stackoverflow
Solution 3 - node.jskushView Answer on Stackoverflow
Solution 4 - node.jsSaifullahView Answer on Stackoverflow