Search code examples
expresssequelize.js

Sequelize include return single record instead all


Using sequelize with expressjs, strangely sequelize return single record instead more than one. There are many records are inserted in shipping_addresses table against a single user. I don't want to remove raw:true it's because that result belongs to graphql that's why using raw:true,

shipping_addresses.belongsTo(users, { as: "userId", foreignKey: "userId"});
users.hasMany(shipping_addresses, { as: "shipping_addresses", foreignKey: "userId"});


sequelize.users.findOne({
    where:{...},
    include: [model:shipping_addresses, as:'shipping_addresses'],
    raw:true,
    nest:true
}).

Here is result

{ 
    id:1, 
    username:johndeo
    shipping_addresses: {
        id:1
        line:abc street
    }
}

What I am expecting

{ 
    id:1, 
    username:johndeo
    shipping_addresses: [
        {
            id:1
            line:abc street
        },
        {
            id:2
            line:another street
        },
    ]
}

Solution

  • https://sequelize.org/api/v6/class/src/model.js~Model.html#instance-method-get

    You don't need raw: true option. Instead, call get({plain: true})

    Sample Code

    async function test() {
        const row = await Users.findOne({
            attributes: ['id', 'username'],
            where: { id: 1 },
            include: [{ model: ShippingAddresses, attributes: ['id', 'line'], as: 'shipping_addresses' }],
            nest: true
        });
        console.log(row.get({ plain: true }))
    }
    
    test()
    

    Result

    $ node test
    {"pid":25056,"sql":"Executing (default): SELECT \"users\".\"id\", \"users\".\"username\", \"shipping_addresses\".\"id\" AS \"shipping_addresses.id\", \"shipping_addresses\".\"line\" AS \"shipping_addresses.line\" FROM \"users\" AS \"users\" LEFT OUTER JOIN \"shipping_addresses\" AS \"shipping_addresses\" ON \"users\".\"id\" = \"shipping_addresses\".\"user_id\" WHERE \"users\".\"id\" = 1;"}
    {
      id: 1,
      username: 'johndeo',
      shipping_addresses: [ { id: 1, line: 'abc street' }, { id: 2, line: 'another street' } ]
    }