rari
rari

Reputation: 155

How to add two records in a row?

When I want to add two records in sequence, only one record is added, on the second it throws an error due to the fact that it cannot create a field with such data:

"NOTES_ID is required","key: NOTES_ID, value: undefined, is not a number"

How to create an entry for two related tables sequentially from the beginning for the main table, and then for the one that has the foreign key installed.

module.exports.create = async function (req, res) {
  const stateMatrix = await StateMatrix.select().exec()

  const noteObj = {
    DATE: req.body.DATE,
    TITLE: req.body.TITLE,
    CONTENT: req.body.CONTENT
  };

  const noteStateObj = {
    STATE_DATE: new Date().toLocaleDateString("en-US"),
    STATES_ID: stateMatrix[0]._props.STATES_ID_CURR,
    NOTES_ID: req.body.NOTE_ID,
    USERS_ID: req.decoded.user_id
  };
  try {
    await Notes.create(noteObj);
    await NoteStates.create(noteStateObj);
    res.status(201).json(noteObj, noteStateObj);
  } catch (e) {
    errorHandler(res, e);
  }
};

Upvotes: 1

Views: 38

Answers (1)

rkm
rkm

Reputation: 3131

Probably NoteStates is related to Notes through note_id field which can not be empty (I guess it's foreign key). It means that you should set it before saving noteStateObj:

// Something like this
const newNote = await Notes.create(noteObj);
noteStateObj.NOTES_ID = newNote.ID;
await NoteStates.create(noteStateObj);

Upvotes: 1

Related Questions