3

I want to get updated table values after I add user to my "WOD" table. For instance, I have 2 users in my WOD table and after I add third user , I want to return a response to client with I have just inserted data (third guy). But now , I can only return first 2 users because I can not take updated values. Of course I can make another query to get updated table values after I insert, but is there any better solution ? Here is my codes;

const addUser = async (req, res) => {
 try {
const { userId, wodId } = req.body;

if (!userId || !wodId) {
  res.status(400).send({ status: false, message: 'need userId and wodId' });
}

const wod = await Wod.findByPk(wodId, {
  include: [
    {
      model: User,
      as: 'Participants',
      through: { attributes: [] }
    }
  ]
});
//check capacity if full.
if (wod.Participants.length >= wod.capacity) {
  res
    .status(403)
    .send({ status: false, message: 'Capacity of this class is full!' });
}
const result = await wod.addParticipants(userId);

res.status(201).json({ status: !!result, wod });
} catch (error) {
res.status(500).send({ status: result, message: error.message });
console.log(error.message);
  }
};

1 Answer 1

3

As a result of many-to-many association sequelize.sync will generate some functions for us. You are used addParticipants function and this returns an array that added to the assocation(userwod) table.

In this array you will find some id fields(join table fields) because you just run like this INSERT INTO 'user_wods' ('user_id''wod_id') VALUES (2,1). If you want to return the added user's information then you should run a SELECT * FROM 'user' WHERE 'id'=2.

You must call reload function for fetch the third guy.

await wod.reload()
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot buddy. I have not known reload method. It works (update object without creating another one.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.