首页 > 解决方案 > 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”。

标签: node.jssequelize.js

解决方案


要么使用 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'
})
})

确保您至少找到了一个用户,否则请为此添加检查。


推荐阅读