我正试图在表中插入一个条目"消息";通过从表"传递一个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,先查找用户,然后创建消息OR在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'
})
})
请确保您至少找到一个用户,否则请为此添加一个检查。