【问题标题】:Why spread() method doesn't work in Sequelize?为什么 spread() 方法在 Sequelize 中不起作用?
【发布时间】:2019-04-02 04:50:43
【问题描述】:

我正在为我的node.js 应用程序使用Sequelize。如果不存在,我使用findOrCreate() 方法创建一个新用户。根据docs findOrCreate 返回一个包含已找到或创建的对象的数组和一个布尔值,如果创建了新对象则为true,否则为false。

sequelize 推荐使用spread() 方法,该方法将数组分成两部分并将它们作为参数传递给回调函数。第一部分是用户对象,第二部分是布尔值(如果添加了新行)。

我以async/await 风格工作。我的代码是:

app.post('/signup', async (req, res) => {
        try {
            let insertedUser = await User.findOrCreate({
                where: { email: req.body.userEmail },
                defaults: {
                    pass: req.body.userPass
                }
            })
            insertedUser.spread((user, created) => {
                if(created) {
                    res.json(user.email)
                }
            })
        } catch (err) {
            console.log(`ERROR! => ${err.name}: ${err.message}`)
            res.status(500).send(err.message)
        }
    }
})

发布请求后我收到一个错误:

ERROR! => TypeError: insertedUser.spread is not a function

为什么会这样,文档说它必须是一个函数?

【问题讨论】:

    标签: javascript node.js sequelize.js


    【解决方案1】:

    spread 方法在来自 findOrCreate 的解析值上不存在。您必须将spreadpromise 返回的then 链接findOrCreate。或者您需要直接与findOrCreate 链接并使用await

    这是带有await的更新代码:

    app.post('/signup', async (req, res) => {
            try {
                let created = await User.findOrCreate({
                    where: { email: req.body.userEmail },
                    defaults: {
                        pass: req.body.userPass
                    }
                }).spread((user, created) => {
                    return created;
                })
                if(created) {
                    res.json(user.email)
                }
            } catch (err) {
                console.log(`ERROR! => ${err.name}: ${err.message}`)
                res.status(500).send(err.message)
            }
        }
    })
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-03
    • 2019-07-18
    • 2016-09-04
    • 1970-01-01
    • 2020-10-02
    • 2011-03-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多