Skip to content
Advertisement

Sequelize relationship query returns duplicate data

I’m querying customer orders for a specified customer using Sequelize relationships.

index.js

var results2 = await customerService.getOrders(1);
console.log(results2);   

service.js

exports.getOrders = function (id) {
    return customerModel.findAll({
        raw: true,
        include: [{
            model: orderModel,
            where: { customer_idcustomer: id }
        }],

    }).then(r => r);
};

results

[ { idcustomer: 1,
    customername: 'hello world',
    'orders.idorder': 1,
    'orders.orderdesc': 'order description 1',
    'orders.customer_idcustomer': 1 },
  { idcustomer: 1,
    customername: 'hello world',
    'orders.idorder': 2,
    'orders.orderdesc': 'Test 456',
    'orders.customer_idcustomer': 1 },
  { idcustomer: 1,
    customername: 'hello world',
    'orders.idorder': 3,
    'orders.orderdesc': 'Test 123',
    'orders.customer_idcustomer': 1 } ]

expected

[ { idcustomer: 1,
    customername: 'hello world',
    'orders: [{
       'orders.idorder': 1,
       'orders.orderdesc': 'order description 1',
       'orders.customer_idcustomer': 1 },   
    },
    {
       'orders.idorder': 2,
       'orders.orderdesc': 'order description 2',
       'orders.customer_idcustomer': 1 },   
    },
    {
       'orders.idorder': 3,
       'orders.orderdesc': 'order description 3',
       'orders.customer_idcustomer': 1 },   
    }]
]

Advertisement

Answer

All you need is to remove raw: true, from query ,

as it will return plain/flat object , and that will convert your object as it looks now.

exports.getOrders = function (id) {
    return customerModel.findAll({
        // raw: true, // <------ Just remove this line
        include: [{
            model: orderModel,
            where: { customer_idcustomer: id }
        }],

    }).then(r => r);
};

Note : You should put the where condition in upper level as per your logic

exports.getOrders = function (id) {
    return customerModel.findAll({
        where: { id: id } ,
        // raw: true, // <------ Just remove this line
        include: [{
            model: orderModel
        }]
    }).then(r => r);
};
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement