How to replace create with findOrCreate in sequelize

Viewed 196

I have a db containing books and writers in M:N relationship using authors association table. I am trying to save multiple books having 0..n writers each. I am running sequelize 6.6.2, sqlite 5 (in dev mode) and pg 8.5.1 (in prod mode) node modules, npm 6.15.8, node v14.16.0. I do not use cls mode, neither I define transactions manualy.

Current code part looks like this and works as expected

          books.forEach(book => {
                //create each book
                db.models.Book.create({
                    name: book.name,
                    edition: book.edition
                }).then(savedBook => {
                    //if book has authors, create the ones, that dont exist
                    if (book.authors) {
                        Promise.all(book.authors
                            .map(author => db.models.Writer.create(author))
                        ).then(savedWriters => {
                            log.debug('savedWriters', savedWriters)
                            Promise.all(
                                // and create relation to book for each of them
                                savedWriters.map(writer => writer.dataValues)
                                    .map(writer => db.models.Author.create({
                                        bookId: savedBook.id,
                                        writerId: writer.id
                                    }))
                            ).then(() => {
                                log.debug('authors saved')
                                callback()
                            }).catch(function (err) {
                                log.error('Error while saving authors ', err)
                            })
                        }).catch(function (err) {
                            log.error('Error while saving writers ', err)
                        })
                    } else {
                        callback()
                    }
                })

but when I change the db.models.Writer.create to db.models.Writer.findOrCreate I get exceptions about transactions

[SequelizeDatabaseError]: SQLITE_ERROR: cannot start a transaction within a transaction

For completenes, exception does not occur when saving multiple books without authors, neither when saving one book with multiple authors. How could I achieve the state of not creating writer every time a book is created, if the writer already exists? Why is create behaviour different than findOrCreate? Thank you in advance.

0 Answers
Related