Chris
Chris

Reputation: 1038

Sequelize JS: How to remove nested object in result set

When using sequelize.js how can I specify that the returned object does not contain included models as nested objects.

E.G.:

Model1.findAll({
  include: [{ model: Model2 }]
})

this will return:

{ id: X, ..., Model2: { ... } }

but I would like to get

{ id: X, ..., <model2 attributes> }

Upvotes: 1

Views: 1934

Answers (1)

Ivan Drinchev
Ivan Drinchev

Reputation: 19581

There is no way to do that without modifying the result object.

You have two options :

var _ = require("lodash");

Model1
    .findAll()
    .then( function( instance1 ) { 
        return instance1
            .getModel2()
            .then( function( instance2 ) {
                return _.extend(instance1.toJSON(), instance2.toJSON() );
            });
    }).then( function( instance1 ) { console.log(instance1) } );

This will create two database queries.

Your second option would be :

var _ = require("lodash");

Model1
    .findAll({
        include: [{ model: Model2 }]
    })
    .then( function( instance1 ) { return instance1.toJSON() } )
    .then( function( instance1 ) {
        var flatInstance = _.extend(instance1, instance1['Model2']);
        delete flatInstance['Model2'];
        return flatInstance;
    })
    .then( function( instance1 ) { console.log(instance1) } );

Which will use only one query.

Upvotes: 2

Related Questions