node.js - Sequelize:如何将 findAll 结果作为 Model.create 值传递
问题描述
我试图通过从表“用户”传递一个 ID 来将一个条目插入到表“消息”中以用作条目值,但我得到一个“val.replace 不是函数错误”。这是我的代码:
Message.create({
userId:
Users.findAll({
where: { username: "sam123" },
attributes: ['id'],
plain: true
}).then((result) => {
console.log(result.id)
return result.id
}),
roomname: 'lobby',
message: 'testing'
})
我的控制台日志返回正确的 ID 号,但没有将该号码传递给“userId”。
解决方案
要么使用 async/await 并首先找到一个用户,然后创建一条消息,要么在then
回调中创建一条消息。顺便说一句,您是否userId
包含一组用户 ID?因为Users.findAll
返回一个对象数组。
第一个解决方案:
// here we get first user that satisfies our condition
const foundUser = await Users.findOne({
where: { username: "sam123" },
attributes: ['id'],
plain: true
})
await Message.create({
userId: foundUser.id,
roomname: 'lobby',
message: 'testing'
})
第二种解决方案
// here we get first user that satisfies our condition
Users.findOne({
where: { username: "sam123" },
attributes: ['id'],
plain: true
}).then((result) => {
Message.create({
userId: result.id,
roomname: 'lobby',
message: 'testing'
})
})
确保您至少找到了一个用户,否则请为此添加检查。
推荐阅读
- excel - 如何使用和 if 语句模拟排队论
- swift - 如何正确处理多个 if else 条件?
- mysql - 为什么我超出了双范围被破坏的范围错误?
- ios - Coredata 获取请求结果在每次请求后翻倍
- python - 无法在模板上显示数据库中的数据
- powershell - 为没有管理员权限的 CurrenUser/LocalMachine 安装证书?
- blender - 根据搅拌机中的光线使物体消失
- c# - 使用 Unity 绘图应用程序
- google-cloud-platform - 如何为 Cloud Run on GKE 服务设置最小规模?
- c# - HttpClient ReadAsStringAsync 舍入小数