首页 > 解决方案 > 如何连续添加两条记录?

问题描述

当我想按顺序添加两条记录时,只添加一条记录,第二条记录由于无法创建包含此类数据的字段而引发错误:

"NOTES_ID 是必需的","key: NOTES_ID, value: undefined, 不是数字"

如何为两个相关表从主表开始顺序创建条目,然后为已安装外键的表创建条目。

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);
  }
};

标签: node.jsexpress

解决方案


可能NoteStates与不能为空的Notesthrough字段有关(我猜它是外键)。note_id这意味着您应该在保存之前设置它noteStateObj

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

推荐阅读