javascript - 尽管它存在于 DB 中,但 Promise 返回 null 值
问题描述
我正在尝试为学校创建一个数据库。在这个数据库中,我想存储带有引用表的属性sessionId
的类名。foreign key
session
同样,我students
用外键存储classId
students
第一行的数组来自其他完美工作的函数。
当我创建新会话然后存储在数据库中并且newSession
变量也获得值时,问题就在这里,但它不在类创建中。它是空的。这里sessionId: newSession.id
它是空的。
类似的类以空值存储在数据库中,sessionId
并且在创建时Student
为newClass.id
空。虽然类完全存储在数据库中。
代码有什么问题?为什么newClass.id
和在创建和newSession.id
时为空Student
Class
students.forEach(async function(student) {
//Create Session
let newSession = await Session.findOrCreate({
where: {
name: student.session,
startDate: student.sStartDate,
endDate: sEndDate
}
})
.then(newSession => {
return newSession;
})
.catch(err => console.log(err));
//Create Class
let newClass = await Class.findOrCreate({
where: {
name: student.class
},
defaults: {
name: student.class,
sessionId: newSession.id
}
})
.then(newClass => {
return newClass;
})
.catch(err => console.log(err));
//Create a student.
Student.findOrCreate({
where: {
id: student.id
},
defaults: {
id: student.id,
name: student.name,
fphone: student.fphone,
fname: student.fname,
classId: newClass.id
}
})
.then(newStudent => {
// console.log(JSON.stringify(newStudent, null, 4));
})
.catch(err => console.log(err));
});
res.send(students);
}
解决方案
根据手册,findOrCreate returns an array containing the object that was found or created and a boolean that will be true
,因此您错误地使用了结果。
https://sequelize.org/master/manual/models-usage.html
尝试这样的事情:
let newSession = null;
try {
const sessionResult = await Session.findOrCreate({
where: {
name: student.session,
startDate: student.sStartDate,
endDate: sEndDate
}
});
newSession = sessionResult[0];
} catch(e) {
console.error(e);
}
此外,如果您正在使用 await,则无需使用 .then 和 .catch。改用 try/catch 来捕获错误。
推荐阅读
- postgresql - init.sql 使用 postgressql 添加为 docker-compose 中的目录
- apache-kafka - 尽管保留设置,Kafka 正在填满磁盘空间
- pandas - 熊猫条件列的总和
- python - s[::-1] 的复杂性是什么,其中`s`是python中的字符串?
- git - 更新使用 Web 界面导入功能创建的 github 存储库
- python - 如何在 Raspbian 上下载 discord.py?
- r - 创建“交叉表”样式输出
- php - 没有深色背景的imagick透明图像
- python - Python SQLalchemy 包......如果数据库在 AWS 上,它肯定是 Redshift 吗?
- python - Python Tkinter 避免在较低级别的函数中使用“root”名称