Node.js Sequelize对象未定义,但存在于上一条then语句中

Node.js Sequelize对象未定义,但存在于上一条then语句中,node.js,express,sequelize.js,Node.js,Express,Sequelize.js,我遇到了一个问题,我试图访问一个对象,但由于某种原因,它被显示为未定义的,尽管在语句的前面创建了该对象,并且能够从单独的then语句访问它 下面是我的post方法逻辑的更好解释。在上一条到/sign-up/organization的路线上创建了一个用户。然后,该用户创建一个组织,该组织在第一个then语句中在成员表中创建用户与组织之间关系的记录。在创建该记录之后,应立即使用创建的组织id更新用户模型 终端输出: Executing (default): INSERT INTO `organiza

我遇到了一个问题,我试图访问一个对象,但由于某种原因,它被显示为
未定义的
,尽管在语句的前面创建了该对象,并且能够从单独的then语句访问它

下面是我的
post
方法逻辑的更好解释。在上一条到
/sign-up/organization
的路线上创建了一个用户。然后,该用户创建一个组织,该组织在第一个then语句中在
成员
表中创建用户与组织之间关系的记录。在创建该记录之后,应立即使用创建的组织id更新用户模型

终端输出:

Executing (default): INSERT INTO `organization` (`organization_id`,`organization_name`,`admin`,`discovery_source`,`updatedAt`,`createdAt`) VALUES (DEFAULT,'Organization Test','test@testg.com','Nice','2016-01-17 19:07:21','2016-01-17 19:07:21'); 
Error at PostTypeError: Cannot read property 'organizationId' of undefined
Executing (default): INSERT INTO `member` (`member_id`,`member_email`,`organization_id`,`user_id`,`updatedAt`,`createdAt`) VALUES (DEFAULT,'tttest@testg.com',4,4,'2016-01-17 19:07:21','2016-01-17 19:07:21');
module.exports = function(sequelize, DataTypes) {


    var Organization = sequelize.define('organization', {
        organizationId: {
            type: DataTypes.INTEGER,
            field: 'organization_id',
            autoIncrement: true,
            primaryKey: true
        },
        organizationName: {
            type: DataTypes.STRING,
            field: 'organization_name'
        },
        admin: DataTypes.STRING,
        discoverySource: {
            type: DataTypes.STRING,
            field: 'discovery_source'
        },
        members: DataTypes.STRING
    },{
        freezeTableName: true,
        classMethods: {
            associate: function(db) {
                Organization.belongsToMany(db.User, { through: 'member', foreignKey: 'user_id' });
            },
        },
    });

        return Organization;
    }
var bcrypt   = require('bcrypt-nodejs');

module.exports = function(sequelize, DataTypes) {

var User = sequelize.define('user', {
    user_id: {
        type: DataTypes.INTEGER,
        autoIncrement: true,
        primaryKey: true
    },
    firstName: {
        type: DataTypes.STRING,
        field: 'first_name'
    },
    lastName: {
        type: DataTypes.STRING,
        field: 'last_name'
    },
    email: {
        type: DataTypes.STRING,
        isEmail: true,
        unique: true
    },
    password: DataTypes.STRING,
    organizationId: {
        type: DataTypes.INTEGER,
        field: 'organization_id',
        allowNull: true
    }
}, {
    freezeTableName: true,
    classMethods: {
        associate: function(db) {
            User.belongsToMany(db.Organization, { through: 'member', foreignKey: 'organizationId'})
        },
        generateHash: function(password) {
            return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
        },
    },
    instanceMethods: {
        validPassword: function(password) {
            return bcrypt.compareSync(password, this.password);
        },
    },


});
    return User;
}
module.exports = function(sequelize, DataTypes) {

var Member = sequelize.define('member', {
    memberId: {
        type: DataTypes.INTEGER,
        field: 'member_id',
        autoIncrement: true,
        primaryKey: true
    },
    memberEmail: {
        type: DataTypes.STRING,
        field: 'member_email'
    },
    organizationId: {
        type: DataTypes.INTEGER,
        field: 'organization_id',
        allowNull: true
    },
    userId: {
        type: DataTypes.INTEGER,
        field: 'user_id',
        allowNull: true
    }
},{
    freezeTableName: true,
});

    return Member;
}
var Sequelize = require('sequelize');
var path = require('path');
var config = require(path.resolve(__dirname, '..', '..','./config/config.js'));
var sequelize = new Sequelize(config.database, config.username, config.password, {
    host:'localhost',
    port:'3306',
    dialect: 'mysql'
});

sequelize.authenticate().then(function(err) {
    if (!!err) {
        console.log('Unable to connect to the database:', err)
    } else {
        console.log('Connection has been established successfully.')
    }
});

var db = {}

db.Member = sequelize.import(__dirname + "/member");

db.Organization = sequelize.import(__dirname + "/organization");

db.User = sequelize.import(__dirname + "/user");

db.Annotation = sequelize.import(__dirname + "/annotation");

db.User.associate(db);
db.Organization.associate(db);
db.Annotation.associate(db);

db.sequelize = sequelize;
db.Sequelize = Sequelize;

sequelize.sync();

module.exports = db;
models.User.update出现错误

路线:

var express = require('express');
var appRoutes   = express.Router();
var passport = require('passport');
var localStrategy = require('passport-local').Strategy;
var models = require('../models/db-index');


appRoutes.route('/sign-up/organization')

    .get(function(req, res){
        models.User.find({
            where: {
                user_id: req.user.email
            }, attributes: [ 'user_id', 'email'
            ]
        }).then(function(user){
            res.render('pages/app/sign-up-organization.hbs',{
                user: req.user
            });
        })  
    })

    .post(function(req, res, user){
        models.Organization.create({
            organizationName: req.body.organizationName,
            admin: req.body.admin,
            discoverySource: req.body.discoverySource
        }).then(function(organization, user){
            organization = organization;
            console.log(organization);
            models.Member.create({
                organizationId: organization.organizationId,
                memberEmail: req.user.email,
                userId: req.user.user_id
            },{ where: { user_id: req.user.user_id }});

        }).then(function(organization, user){
            models.User.update({
                organizationId: organization.organizationId
            });
            res.redirect('/app');
        }).catch(function(error){
            res.send(error);
            console.log('Error at Post' + error);
        })
    });



appRoutes.get('/logout', function(req, res){
    req.logout();
    console.log('User logged out');
    res.redirect('/');
});



module.exports = appRoutes;
page/app/sign-up-organization.hbs:

<!DOCTYPE html>
<head>
    {{> head}}
</head>
<body>
    {{> navigation}}
    <div class="container">
        <div class="col-md-6 col-md-offset-3">
            <form action="/app/sign-up/organization" method="post">
                <p>{{user.email}}</p>
                <input type="hidden" name="admin" value="{{user.email}}">
                <input type="hidden" name="organizationId">
                <label for="sign-up-organization">Company/Organization Name</label>
                <input type="text" class="form-control" id="sign-up-organization"  name="organizationName" value="" placeholder="Company/Organization">
                <a href="#" id="sign-up-add-discovery-source">Add Another Discovery Source</a>
                <div id="sign-up-organization-discovery-source">
                    <input type="text" id="discovery-source-field" placeholder="Discovery Source" name="discoverySource">
                </div>
                <br />
                    <button type="submit">Submit</button>
            </form>
            <a href="/login">Already have an account? Login here!</a>
        </div>
    </div>
</body>
用户:

Executing (default): INSERT INTO `organization` (`organization_id`,`organization_name`,`admin`,`discovery_source`,`updatedAt`,`createdAt`) VALUES (DEFAULT,'Organization Test','test@testg.com','Nice','2016-01-17 19:07:21','2016-01-17 19:07:21'); 
Error at PostTypeError: Cannot read property 'organizationId' of undefined
Executing (default): INSERT INTO `member` (`member_id`,`member_email`,`organization_id`,`user_id`,`updatedAt`,`createdAt`) VALUES (DEFAULT,'tttest@testg.com',4,4,'2016-01-17 19:07:21','2016-01-17 19:07:21');
module.exports = function(sequelize, DataTypes) {


    var Organization = sequelize.define('organization', {
        organizationId: {
            type: DataTypes.INTEGER,
            field: 'organization_id',
            autoIncrement: true,
            primaryKey: true
        },
        organizationName: {
            type: DataTypes.STRING,
            field: 'organization_name'
        },
        admin: DataTypes.STRING,
        discoverySource: {
            type: DataTypes.STRING,
            field: 'discovery_source'
        },
        members: DataTypes.STRING
    },{
        freezeTableName: true,
        classMethods: {
            associate: function(db) {
                Organization.belongsToMany(db.User, { through: 'member', foreignKey: 'user_id' });
            },
        },
    });

        return Organization;
    }
var bcrypt   = require('bcrypt-nodejs');

module.exports = function(sequelize, DataTypes) {

var User = sequelize.define('user', {
    user_id: {
        type: DataTypes.INTEGER,
        autoIncrement: true,
        primaryKey: true
    },
    firstName: {
        type: DataTypes.STRING,
        field: 'first_name'
    },
    lastName: {
        type: DataTypes.STRING,
        field: 'last_name'
    },
    email: {
        type: DataTypes.STRING,
        isEmail: true,
        unique: true
    },
    password: DataTypes.STRING,
    organizationId: {
        type: DataTypes.INTEGER,
        field: 'organization_id',
        allowNull: true
    }
}, {
    freezeTableName: true,
    classMethods: {
        associate: function(db) {
            User.belongsToMany(db.Organization, { through: 'member', foreignKey: 'organizationId'})
        },
        generateHash: function(password) {
            return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
        },
    },
    instanceMethods: {
        validPassword: function(password) {
            return bcrypt.compareSync(password, this.password);
        },
    },


});
    return User;
}
module.exports = function(sequelize, DataTypes) {

var Member = sequelize.define('member', {
    memberId: {
        type: DataTypes.INTEGER,
        field: 'member_id',
        autoIncrement: true,
        primaryKey: true
    },
    memberEmail: {
        type: DataTypes.STRING,
        field: 'member_email'
    },
    organizationId: {
        type: DataTypes.INTEGER,
        field: 'organization_id',
        allowNull: true
    },
    userId: {
        type: DataTypes.INTEGER,
        field: 'user_id',
        allowNull: true
    }
},{
    freezeTableName: true,
});

    return Member;
}
var Sequelize = require('sequelize');
var path = require('path');
var config = require(path.resolve(__dirname, '..', '..','./config/config.js'));
var sequelize = new Sequelize(config.database, config.username, config.password, {
    host:'localhost',
    port:'3306',
    dialect: 'mysql'
});

sequelize.authenticate().then(function(err) {
    if (!!err) {
        console.log('Unable to connect to the database:', err)
    } else {
        console.log('Connection has been established successfully.')
    }
});

var db = {}

db.Member = sequelize.import(__dirname + "/member");

db.Organization = sequelize.import(__dirname + "/organization");

db.User = sequelize.import(__dirname + "/user");

db.Annotation = sequelize.import(__dirname + "/annotation");

db.User.associate(db);
db.Organization.associate(db);
db.Annotation.associate(db);

db.sequelize = sequelize;
db.Sequelize = Sequelize;

sequelize.sync();

module.exports = db;
成员:

Executing (default): INSERT INTO `organization` (`organization_id`,`organization_name`,`admin`,`discovery_source`,`updatedAt`,`createdAt`) VALUES (DEFAULT,'Organization Test','test@testg.com','Nice','2016-01-17 19:07:21','2016-01-17 19:07:21'); 
Error at PostTypeError: Cannot read property 'organizationId' of undefined
Executing (default): INSERT INTO `member` (`member_id`,`member_email`,`organization_id`,`user_id`,`updatedAt`,`createdAt`) VALUES (DEFAULT,'tttest@testg.com',4,4,'2016-01-17 19:07:21','2016-01-17 19:07:21');
module.exports = function(sequelize, DataTypes) {


    var Organization = sequelize.define('organization', {
        organizationId: {
            type: DataTypes.INTEGER,
            field: 'organization_id',
            autoIncrement: true,
            primaryKey: true
        },
        organizationName: {
            type: DataTypes.STRING,
            field: 'organization_name'
        },
        admin: DataTypes.STRING,
        discoverySource: {
            type: DataTypes.STRING,
            field: 'discovery_source'
        },
        members: DataTypes.STRING
    },{
        freezeTableName: true,
        classMethods: {
            associate: function(db) {
                Organization.belongsToMany(db.User, { through: 'member', foreignKey: 'user_id' });
            },
        },
    });

        return Organization;
    }
var bcrypt   = require('bcrypt-nodejs');

module.exports = function(sequelize, DataTypes) {

var User = sequelize.define('user', {
    user_id: {
        type: DataTypes.INTEGER,
        autoIncrement: true,
        primaryKey: true
    },
    firstName: {
        type: DataTypes.STRING,
        field: 'first_name'
    },
    lastName: {
        type: DataTypes.STRING,
        field: 'last_name'
    },
    email: {
        type: DataTypes.STRING,
        isEmail: true,
        unique: true
    },
    password: DataTypes.STRING,
    organizationId: {
        type: DataTypes.INTEGER,
        field: 'organization_id',
        allowNull: true
    }
}, {
    freezeTableName: true,
    classMethods: {
        associate: function(db) {
            User.belongsToMany(db.Organization, { through: 'member', foreignKey: 'organizationId'})
        },
        generateHash: function(password) {
            return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
        },
    },
    instanceMethods: {
        validPassword: function(password) {
            return bcrypt.compareSync(password, this.password);
        },
    },


});
    return User;
}
module.exports = function(sequelize, DataTypes) {

var Member = sequelize.define('member', {
    memberId: {
        type: DataTypes.INTEGER,
        field: 'member_id',
        autoIncrement: true,
        primaryKey: true
    },
    memberEmail: {
        type: DataTypes.STRING,
        field: 'member_email'
    },
    organizationId: {
        type: DataTypes.INTEGER,
        field: 'organization_id',
        allowNull: true
    },
    userId: {
        type: DataTypes.INTEGER,
        field: 'user_id',
        allowNull: true
    }
},{
    freezeTableName: true,
});

    return Member;
}
var Sequelize = require('sequelize');
var path = require('path');
var config = require(path.resolve(__dirname, '..', '..','./config/config.js'));
var sequelize = new Sequelize(config.database, config.username, config.password, {
    host:'localhost',
    port:'3306',
    dialect: 'mysql'
});

sequelize.authenticate().then(function(err) {
    if (!!err) {
        console.log('Unable to connect to the database:', err)
    } else {
        console.log('Connection has been established successfully.')
    }
});

var db = {}

db.Member = sequelize.import(__dirname + "/member");

db.Organization = sequelize.import(__dirname + "/organization");

db.User = sequelize.import(__dirname + "/user");

db.Annotation = sequelize.import(__dirname + "/annotation");

db.User.associate(db);
db.Organization.associate(db);
db.Annotation.associate(db);

db.sequelize = sequelize;
db.Sequelize = Sequelize;

sequelize.sync();

module.exports = db;
db索引:

Executing (default): INSERT INTO `organization` (`organization_id`,`organization_name`,`admin`,`discovery_source`,`updatedAt`,`createdAt`) VALUES (DEFAULT,'Organization Test','test@testg.com','Nice','2016-01-17 19:07:21','2016-01-17 19:07:21'); 
Error at PostTypeError: Cannot read property 'organizationId' of undefined
Executing (default): INSERT INTO `member` (`member_id`,`member_email`,`organization_id`,`user_id`,`updatedAt`,`createdAt`) VALUES (DEFAULT,'tttest@testg.com',4,4,'2016-01-17 19:07:21','2016-01-17 19:07:21');
module.exports = function(sequelize, DataTypes) {


    var Organization = sequelize.define('organization', {
        organizationId: {
            type: DataTypes.INTEGER,
            field: 'organization_id',
            autoIncrement: true,
            primaryKey: true
        },
        organizationName: {
            type: DataTypes.STRING,
            field: 'organization_name'
        },
        admin: DataTypes.STRING,
        discoverySource: {
            type: DataTypes.STRING,
            field: 'discovery_source'
        },
        members: DataTypes.STRING
    },{
        freezeTableName: true,
        classMethods: {
            associate: function(db) {
                Organization.belongsToMany(db.User, { through: 'member', foreignKey: 'user_id' });
            },
        },
    });

        return Organization;
    }
var bcrypt   = require('bcrypt-nodejs');

module.exports = function(sequelize, DataTypes) {

var User = sequelize.define('user', {
    user_id: {
        type: DataTypes.INTEGER,
        autoIncrement: true,
        primaryKey: true
    },
    firstName: {
        type: DataTypes.STRING,
        field: 'first_name'
    },
    lastName: {
        type: DataTypes.STRING,
        field: 'last_name'
    },
    email: {
        type: DataTypes.STRING,
        isEmail: true,
        unique: true
    },
    password: DataTypes.STRING,
    organizationId: {
        type: DataTypes.INTEGER,
        field: 'organization_id',
        allowNull: true
    }
}, {
    freezeTableName: true,
    classMethods: {
        associate: function(db) {
            User.belongsToMany(db.Organization, { through: 'member', foreignKey: 'organizationId'})
        },
        generateHash: function(password) {
            return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
        },
    },
    instanceMethods: {
        validPassword: function(password) {
            return bcrypt.compareSync(password, this.password);
        },
    },


});
    return User;
}
module.exports = function(sequelize, DataTypes) {

var Member = sequelize.define('member', {
    memberId: {
        type: DataTypes.INTEGER,
        field: 'member_id',
        autoIncrement: true,
        primaryKey: true
    },
    memberEmail: {
        type: DataTypes.STRING,
        field: 'member_email'
    },
    organizationId: {
        type: DataTypes.INTEGER,
        field: 'organization_id',
        allowNull: true
    },
    userId: {
        type: DataTypes.INTEGER,
        field: 'user_id',
        allowNull: true
    }
},{
    freezeTableName: true,
});

    return Member;
}
var Sequelize = require('sequelize');
var path = require('path');
var config = require(path.resolve(__dirname, '..', '..','./config/config.js'));
var sequelize = new Sequelize(config.database, config.username, config.password, {
    host:'localhost',
    port:'3306',
    dialect: 'mysql'
});

sequelize.authenticate().then(function(err) {
    if (!!err) {
        console.log('Unable to connect to the database:', err)
    } else {
        console.log('Connection has been established successfully.')
    }
});

var db = {}

db.Member = sequelize.import(__dirname + "/member");

db.Organization = sequelize.import(__dirname + "/organization");

db.User = sequelize.import(__dirname + "/user");

db.Annotation = sequelize.import(__dirname + "/annotation");

db.User.associate(db);
db.Organization.associate(db);
db.Annotation.associate(db);

db.sequelize = sequelize;
db.Sequelize = Sequelize;

sequelize.sync();

module.exports = db;

要在另一个then语句中使用从then语句获得的
Promise
对象,需要返回
Promise
对象

您需要返回在
post
方法的第一次“then”调用中获得的
organization
对象:

...
.post(function(req, res, user){
    models.Organization.create({
        organizationName: req.body.organizationName,
        admin: req.body.admin,
        discoverySource: req.body.discoverySource
    }).then(function(organization, user){
        organization = organization;
        console.log(organization);
        models.Member.create({
            organizationId: organization.organizationId,
            memberEmail: req.user.email,
            userId: req.user.user_id
        },{ where: { user_id: req.user.user_id }});
        // Return the organization Promise instance here to make it
        // available in the next then statememt
        return organization;
    }).then(function(organization, user){
        models.User.update({
            organizationId: organization.organizationId
        });
        res.redirect('/app');
    }).catch(function(error){
        res.send(error);
        console.log('Error at Post' + error);
    })
});

能否显示错误并突出显示产生错误的代码块?这会让一个人更容易回答你的问题。很抱歉。我用终端输出更新了问题谢谢。您可能需要从帖子中删除与问题无关的任何文件。这使问题更容易阅读。