与Sequelize的交易不起作用

时间:2014-12-31 02:11:06

标签: sql node.js transactions promise sequelize.js

我想构建一个简单的网络表单,您可以在其中输入人员名字,姓氏并为此人选择多个组(但现在只有一个)

我正在使用node.js和sequelize将此人存储在MariaDB -Database中。

Sequelize根据定义的模型创建了表 Persons Groups GroupsPersons

var Sequelize = require("sequelize");
var sequelize = new Sequelize(config.database, config.username, config.password, config);

var Group = sequelize.define("Group", {
    name: {
        type: DataTypes.STRING,
        allowNull: false
    }
}

var Person = sequelize.define("Person", {
    firstName: {
        type: DataTypes.STRING,
        allowNull: false
    },
    lastName: {
      type: DataTypes.STRING,
      allowNull: false
    }
}


Person.belongsToMany(Group, {as: 'Groups'});
Group.belongsToMany(Person, {as: 'Persons'});

因为创建人员并将其分配到组中应该在一个步骤中以原子方式处理我决定使用事务,如此处的文档中所示: http://sequelize.readthedocs.org/en/latest/docs/transactions/#using-transactions-with-other-sequelize-methods

var newPerson = {
    firstName: 'Hans',
    lastName: 'Fischer'
}
var id = 3    // group

sequelize.transaction(function (t) {
    return Person.create(newPerson, {transaction: t}).then(function (person) {
        return Group.find(id, {transction: t}).then(function(group){
            if (!group) throw Error("Group not found for id: " + id);
            return person.setGroups( [group], {transction: t});
        })              

    });
}).then(function (result) {
    // Transaction has been committed
    // result is whatever the result of the promise chain returned to the transaction callback is
    console.log(result);
}).catch(function (err) {
    // Transaction has been rolled back
    // err is whatever rejected the promise chain returned to the transaction callback is
    console.error(err);
});`

但由于某种原因,成功的function (result) {..和catch中的函数都不会被调用。但是,除了COMMIT之外,生成了事务的完整SQL查询,因此没有任何内容插入到数据库中。

如果我这样说的话     return person.setGroups( [], {transction: t}); 事务成功,但当然没有插入 GroupsPersons

有任何想法或建议吗?

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

{transaction:t}拼写错误,现在可以使用了