Skip to content

Instantly share code, notes, and snippets.

@deeja
Last active May 9, 2020 15:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save deeja/e8eb36d04214c67e96a44dc7721d1a59 to your computer and use it in GitHub Desktop.
Save deeja/e8eb36d04214c67e96a44dc7721d1a59 to your computer and use it in GitHub Desktop.
Node.js - Sequelize Model Setup
const { DataTypes } = require("sequelize");
module.exports = {
name: "Breed",
modelName: "breed",
schema: {
name: {
type: DataTypes.STRING,
allowNull: false,
}
},
};
const { DataTypes, Deferrable } = require("sequelize");
const breed = require('./Breed')
module.exports = {
name: "BreedImage",
modelName: "breed_image",
schema: {
breed_id: {
type: DataTypes.INTEGER,
references: {
// This is a reference to another model
model: breed.modelName,
// This is the column name of the referenced model
key: 'id',
// This declares when to check the foreign key constraint. PostgreSQL only.
deferrable: Deferrable.INITIALLY_IMMEDIATE
}
},
image_src: {
type: DataTypes.STRING,
allowNull: false,
},
},
};
function getModels(sequelize) {
const models = [require("./Breed"), require("./BreedImage")];
const result = {};
for (const model of models) {
result[model.name] = modelFactory(sequelize, model);
}
return result;
}
const modelFactory = (sequelize, modelDefinition) => {
const customModel = sequelize.define(
modelDefinition.name,
modelDefinition.schema,
{
sequelize,
modelName: modelDefinition.modelName || modelDefinition.name,
}
);
return customModel;
};
module.exports = {
getModels,
};
const Sequelize = require("sequelize");
const Keys = require("./keys");
const {getModels} = require("./ModelFactory")
const sequelize = new Sequelize(Keys.PGDATABASE, Keys.PGUSER, Keys.PGPASSWORD, {
host: Keys.PGHOST,
dialect: "postgres",
});
const models = getModels(sequelize);
// Sync the table and add the breed
models.BreedImage.sync({ force: true }).then(() => {
return models.BreedImage.create({
breed: "Collie",
image:"myimage.jpg"
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment