Node js and Sequelize insert to database

时间:2018-03-09 19:17:14

标签: node.js express model insert sequelize.js

In my project I am using MySQL database and Sequelize Js, I have two models created:

Post code model:

module.exports = function(sequelize, Sequelize) {

var Post_code = sequelize.define('post_code', {

    id: {
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER(11)
    },

    code: {
        type: Sequelize.STRING(16),
        allowNull: false,
        unique: true
    },

    city: {
        type: Sequelize.STRING(45),
        allowNull: false
    }
},{
    freezeTableName: true,
    underscored: true
});

Post_code.associate = function(models) {
    models.post_code.hasMany(models.building);
};

   return Post_code;
}

Building model:

module.exports = function(sequelize, Sequelize) {

var Building = sequelize.define('building', {

    id: {
        autoIncrement: true,
        primaryKey: true,
        allowNull: false,
        type: Sequelize.INTEGER(11)
    },

    name: {
        type: Sequelize.STRING(100),
        allowNull: false
    },

    number: {
        type: Sequelize.INTEGER(11),
        allowNull: false
    },

    address: {
        type: Sequelize.STRING(255),
        allowNull: false
    },

    latitude: {
        type: Sequelize.DECIMAL(9,6),
        allowNull: false
    },

    longitude: {
        type: Sequelize.DECIMAL(9,6),
        allowNull: false
    }
},{
    freezeTableName: true,
    underscored: true
});

Building.associate = function (models) {
    models.building.belongsTo(models.post_code, {
        foreignKey: {
            allowNull: false
        }
    });

    models.building.hasMany(models.flat);
};

    return Building;
};

They are in relation one to many, it follows that Post code has many Buildings:

enter image description here

I want to add new building to database, when POST request is send to this route:

"/post-codes/:post_code_id/buildings"

I have access to post_code_id but I don't know how to correctly associate post_code model with building.

I was trying to do something like this:

models.post_code.findById(req.params.post_code_id)
.then(function(postCode){
    postCode.setBuilding(
        models.building.create({
        }).then(function(building){});  
    );    
});

But without result. I would be grateful if someone could explain how to make inserts correctly.

1 个答案:

答案 0 :(得分:1)

我还没有听说过关于create的include选项,但你可以这样做:

db.post_code.find({
  where: {
    id: req.params.post_code_id
  }
}).then(post_code => {
  if (!post_code) {
    return res.status(404).send({
      message: 'No post_code with that identifier has been found'
    });
  } else {
    //create here your building
  }
}).catch(err => {
  return res.jsonp(err)
});

我不知道这是否是最好的方法,但它首先验证post_code是否存在。