0

I'm trying to reload a model in order to include association. This is my code:

const order = new Order({ total: 0 })

return order.save().then(savedOrder => {

    const orderItems = req.body.items.map(i => {
        return Eliquid.findByPk(i.eliquid).then(eliquid => {

         const item = Item.build({
           qty: i.qty,
           n: i.n,
         })

         item.setEliquid(eliquid)
         item.setOrder(savedOrder)

         return item
             .save().then(i => {
                 console.log('Saved, has id, has qty', i.id, i.qty)
                 return i.reload()
              })
              .then(i => {
                  console.log('Reloaded, qty is now NULL!', i.id, i.qty)
                  return i
              })
         })
    })

Why after reloading my instance it gets whiped out? Don't know what I'm doing wrong

danielrvt
  • 10,177
  • 20
  • 80
  • 121

1 Answers1

1

As far as I can tell, .reload() (unlike .save()) doesn't deliver the item back to the client; instead, it synchronises the original item's properties with those on the server.

I'm not sure you actually need to reload in this case because client & server representations of the item will automatically be in sync immediately after .save(), but here's an example of how you would exploit javascript's "closure" to maintain access to the item, after .reload().

const order = new Order({ 'total': 0 });
return order.save()
.then(savedOrder => {
    const orderItems = req.body.items.map(i => {
        return Eliquid.findByPk(i.eliquid)
        .then(eliquid => {
            const item = Item.build({ 'qty': i.qty, 'n': i.n });
            item.setEliquid(eliquid);
            item.setOrder(savedOrder);
            return item.save();
        })
        .then(ii => {
            console.log('Saved, has id, has qty', ii.id, ii.qty);
            return ii.reload()
            .then(() => { // .reload() does not repeat item back to client
                console.log('same ii as before', ii.id, ii.qty); // here, access ii through closure.
                return ii;
            });
        });
    });
});

Notes:

  • for clarity ii is used in the second .then() callback to avoid reusing the .map() callback's symbol i.
  • the inner promise chain is flattened as far as possible. If you needed access to eliquid in the second inner .then(), you would need to revert to return item.save().then() and incur a futher level of nesting.
  • in addition to exploiting closure, other approaches exit - see the comprehensive answers here.
Roamer-1888
  • 19,138
  • 5
  • 33
  • 44