gpt4 book ai didi

node.js - Sequelize : how to pass findAll result as Model. 创造值(value)

转载 作者:行者123 更新时间:2023-12-03 22:25:20 25 4
gpt4 key购买 nike

我试图通过从表“用户”传递一个 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'
})
})
确保您找到了至少一个用户,否则请为此添加一个检查。

关于node.js - Sequelize : how to pass findAll result as Model. 创造值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63673557/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com