node.js - 如何连续添加两条记录?
问题描述
当我想按顺序添加两条记录时,只添加一条记录,第二条记录由于无法创建包含此类数据的字段而引发错误:
"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);
}
};
解决方案
可能NoteStates
与不能为空的Notes
through字段有关(我猜它是外键)。note_id
这意味着您应该在保存之前设置它noteStateObj
:
// Something like this
const newNote = await Notes.create(noteObj);
noteStateObj.NOTES_ID = newNote.ID;
await NoteStates.create(noteStateObj);
推荐阅读
- c++ - OpenGL - 渲染到单通道纹理?
- javascript - Webscrape Json 使用 Excel VBA 使用 VBA-JSON 插件
- python - 在鼻子测试框架 Python Qualis 中获取 AssertionError
- shell - Apple Automator / Scripting - 将同一图像调整为多种尺寸
- azure - 在 Azure webjob 上运行 Windows 任务计划程序作业(计划事件)
- swiftui - 单击列表行中的 NavigationLink 后无法弹出到根视图
- python - Python:尝试使用 SO 答案,得到 --> NameError: name 'timeout' is not defined
- html - 制作
- apollo - 如何在 Flow 中正确键入 Apollo Client 实例?
- python - 通过 Python、树莓派将传感器数据输入 MySQL