Search code examples
node.jspostgresqlschemasequelize.jsdatabase-schema

Sequelize schema for PostgreSQL: How to accurately define a schema in a model?


I searched throughout the net and have not been able to determine how to add a schema to this sequelize model below. The following code does not kick back errors, however when I inspect the postgres DB, the only schema is the default one for public.

// The model definition is done in /path/to/models/project.js
module.exports = function(sequelize, DataTypes) {
  return sequelize.define("project", {
    name: DataTypes.STRING,
    description: DataTypes.TEXT,
  },
    define: {
        schema: "prefix"
    },
    classMethods: {
      method1: function() {},
      method2: function() {}
  },
    instanceMethods: {
      method3: function() {}
  })

How should the script be revised to accurately define a schema?

EDIT

In my case, the final answer was

 database_name.sequelize.createSchema('prefix').then(() => {...});

in my ./models/index.js file the database object is as follows:

database_name = {
    Sequelize: Sequelize,
    sequelize: sq,
    table_1: sq.import(__dirname + '/file_folder')
 };

module.exports = database_name;

Solution

  • Your model definition should look as follows

    module.exports = function(sequelize, DataTypes) {
    
        return sequelize.define("project", {
            name: DataTypes.STRING,
            description: DataTypes.TEXT,
        }, {
            schema: 'prefix',
            classMethods: {
                method1: function() {},
                method2: function() {}
            },
            instanceMethods: {
                method3: function() {}
            }
        }
    }
    

    According to the documentation of options object in sequelize.define method, it can have attribute called schema.

    EDIT - Creating schema programatically

    In order to create a new schema (only for PostgreSQL!), you can use the sequelize.createSchema() method:

    sequelize.createSchema('prefix').then(() => {
        // new schema is created
    });
    

    Above creates given SQL

    CREATE SCHEMA prefix;
    

    In order to use this schema in model definitions, you need to create the schema before synchronising any model into the database - it could be run before sequelize.sync() or, if you use migrations, as a first migration file.