express - Sequelize 创建对象后无法更新关联记录

标签 express sequelize.js

我遇到了一个问题,我似乎无法显示我新创建的记录(“组织”),从该记录中获取一个值(“organization.organizationId”),然后在更新记录的值(“用户.organizationId”)在另一个表中。我看到了 INSERT INTOUPDATE 的 SQL 命令,但在 UPDATE 中没有找到任何值。这对我来说没有意义,因为 console.log(organization); 像这样显示对象:

{ dataValues: 
   { organizationId: 18,
     organizationName: 'sdfsafnuffd',
     admin: 'jdofsdjf@mfsdfa.com',
     members: 'jdofsdjf@mfsdfa.com',
     updatedAt: Mon Jan 11 2016 21:07:44 GMT-0500 (EST),
     createdAt: Mon Jan 11 2016 21:07:44 GMT-0500 (EST) },

以下是我的 route 的 SQL 命令:

插入:
Executing (default): INSERT INTO `organization` (`organization_id`,`organization_name`,`admin`,`members`,`updatedAt`,`createdAt`) VALUES (DEFAULT,'sdfsafnuffd','jdofsdjf@mfsdfa.com','jdofsdjf@mfsdfa.com','2016-01-12 02:07:44','2016-01-12 02:07:44');

更新:
Executing (default): UPDATE `user` SET `updatedAt`='2016-01-12 02:07:44' WHERE `user_id` = 18

organization.js 模型:
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,
    members: DataTypes.STRING
},{
    freezeTableName: true,
    classMethods: {
        associate: function(db) {
            Organization.hasMany(db.User, {foreignKey: 'user_id'});
        },
    },
});

    return Organization;
}

user.js 模型:
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.belongsTo(db.Organization)
        },
        generateHash: function(password) {
            return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
        },
    },
    instanceMethods: {
        validPassword: function(password) {
            return bcrypt.compareSync(password, this.password);
        },
    },


});
    return User;
}

db-index.js 设置:
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.Organization = sequelize.import(__dirname + "/organization");

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


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

sequelize.sync();

module.exports = db;

路线:
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,
            members: req.user.email
        }).then(function(organization){
            console.log(organization);
            models.User.update({
                annotationId: organization.organizationId
            },{ where: { user_id: req.user.user_id }});
            res.redirect('/app');
        }).catch(function(error){
            res.send(error);
            console.log('Error at Post' + error);
        })
    });

最佳答案

models.User.update({
            annotationId: organization.organizationId
        },{ where: { user_id: req.user.user_id }});

不确定这是否是类型 o,但 annotationId 似乎没有在您的模型中定义。

关于express - Sequelize 创建对象后无法更新关联记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34734568/

相关文章:

typescript - 对 BelongsToMany 关联的连接表列名进行 Sequelize

node.js - 如何使用 Sequelize 填充树

javascript - Node.js 将 : store req. ip 表达为变量

Heroku cedar 堆栈上的 Node.js 端口问题

node.js - 如何将 websocket 放入数据库(mongoDB/mongoose)?

node.js - Node 路由响应未设置

javascript - 回调函数中的递归

javascript - Sequelize.JS 多对多 findAll 不使用连接表

node.js - 仅当 active = true 时 Sequelize ORM 包含模型

node.js - 如何使用 Sequelize 在迁移中添加对另一个表列的引用作为外键