我有一个问题,我试图访问一个对象,但由于某种原因,尽管在语句中先前创建了对象并且能够从单独的then语句访问它,它仍然以undefined
出现。
以下是我post
方法逻辑的更好解释。在前一个/sign-up/organization
路由中创建了一个用户。然后,该用户创建一个组织,该组织在第一个语句中创建member
表中用户和组织之间关系的记录。创建该记录后,应使用创建的组织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');
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;
网页/应用/签上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>
组织:
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;
答案 0 :(得分:0)
要在另一个 then 语句中使用从 then 语句获取的Promise
对象,您需要返回Promise
对象。
您需要返回在第一个&#39;然后&#39;中获得的organization
个对象。调用post
方法:
...
.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);
})
});
...