Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why spread() method doesn't work in Sequelize?

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.

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.

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?

like image 710
Nastro Avatar asked Oct 29 '18 09:10

Nastro


People also ask

How do I call a function in Sequelize?

sequelize. query('CALL calculateFees();'). success( function (settingName1, settingName2, settingName3, users) { });

What is spread Sequelize?

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.

How do you call a view in Sequelize?

There are no builtin methods for managing views in Sequelize, but you can create them using plain SQL queries and manage them with normal Sequelize models.


1 Answers

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.

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)
        }
    }
})
like image 183
AkshayM Avatar answered Sep 25 '22 00:09

AkshayM