Sequelize through association attributes in Pug

Viewed 9

In a nutshell, I cannot access though association attributes in Pug, only id and created_at can be displayed.

I have Item and Order models, they have many to many relationship though OrderItem model which is hooked to order_items table which works correctly on an API. When orders are sent to Pug using res.render, the resulting object has items which have nested order_items as 'through attributes'. Declared 'through association' attributes in the controller are id, payment, quantity and created_at and they are all seen in the object sent to res.render.

The association is defined in the Order model as:

static associate(models) { Order.belongsToMany(models.Item, {
    as:'items',
    through: 'order_items',
    foreignKey: 'order_id',
    otherKey: 'item_id'
    })
}

On the Item model, similar association is declared with a few changes. On the controller, this is how I call a specific order:

const foundOrder = await Order.findOne({
    where: { id: req.params.id },
    include: {
        model: Item,
        as: 'items',
        through: { attributes: ['id', 'quantity', 'payment', 'created_at']}
    }
})

In views/orders/details I wanted to view details of a specific order, in the rendered result I only got item.name, item.order_items.id and item.order_items.created_at but failed to get item.order_items.quantity or item.order_items.payment which should be on the same tree level as the id.

When I try to loop through the object and console.log(item.order_items) in the server console I see the entire nested object and indeed quantity and payment are there. They are in string format as I have been trying to see if them being INTEGER was the problem but that did not solve anything.

{
   "id":"2ac16f14-75c8-4bb6-b693-f5dc825eb33e",
   "quantity":"34",
   "payment":"136000",
   "created_at":"2022-09-22T10:30:10.000Z"
}{
   "id":"b7f06b43-ac79-4fc6-8e46-01c6c5a8cfd2",
   "quantity":"80",
   "payment":"320000",
   "created_at":"2022-09-22T10:30:10.000Z"
}

Likewise, when I put console.log(item.order_items.id) or created_at in the same style in the order page in Pug I get the values for the two items that are attached with that order.

"2ac16f14-75c8-4bb6-b693-f5dc825eb33e"
"b7f06b43-ac79-4fc6-8e46-01c6c5a8cfd2"

On the other hand, if I put in the same view/orders/details.pug the script console.log(item.order_items.quantity) instead of getting 34 and 80, I get:

unidentified
unidentified

What have I done wrong? Is this a bug with Pug?

0 Answers
Related