为什么 spread() 方法在 Sequelize 中不起作用? [英] Why spread() method doesn't work in Sequelize?

查看:28
本文介绍了为什么 spread() 方法在 Sequelize 中不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using a Sequelize for my node.js app. I use findOrCreate() method to create a new user if not exist. Accordingly to docs findOrCreate returns an array containing the object that was found or created and a boolean that will be true if a new object was created and false if not.

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

The sequelize recommend to use spread() method which divides the array into its 2 parts and passes them as arguments to the callback function. First part is a user object and second is boolean if new row was added.

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

I work in async/await style. My code is:

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)
        }
    }
})

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

After post request I get an error:

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

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

Why is that, the doc says it must be a function?

推荐答案

spread 方法不存在于从 findOrCreate 解析的值上.您必须将spreadfindOrCreate 返回的promisethen 链接起来.或者你需要直接用findOrCreate链接并使用await.

spread method does not exist on resolved value from findOrCreate. You have to either chain spread with then of promise returned by findOrCreate. Or you need to chain with findOrCreate directly and use await.

这是带有 await 的更新代码:

Here is the updated code with 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)
        }
    }
})

这篇关于为什么 spread() 方法在 Sequelize 中不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆