Moon
Moon

Reputation: 149

Bind Sequelize raw query to model

I know Sequelize can use raw query, https://sequelize.org/master/manual/raw-queries.html, to do some customized query action. Is there a way I can create a model method to run my raw query?

For example, if I have a model Project, what I have try is:

on project model file:

const Project = (sequelize, DataTypes) =>
    sequelize.define(
        "Project",
        {
            projectId: {
                type: DataTypes.INTEGER,
                primaryKey: true,
                allowNull: false,
                field: "Project_ID",
                autoIncrement: true,
            },
            ...
            dateUpload: {
                type: DataTypes.DATE,
                field: "Date_Upload",
                defaultValue: Sequelize.NOW,
            },
        }
)


Project.myCustomQuery = async (projectId) => {
   const query = "select * ..."
   const project = await sequelize.query(query)
   return project
}

module.exports = Project

On controller, I use:

const project = Project.myCustomQuery(projectId)

and return this project. However, it gets error saying "Project.myCustomQuery is not a function".

How should I add the function to model class?

Upvotes: 0

Views: 1674

Answers (1)

Aayush Mall
Aayush Mall

Reputation: 1013

You need to add the class/instance methods on the model object which is returned by sequelize.define method

Below model class will work for you

module.exports = (sequelize, DataTypes) => {
    const Project = sequelize.define( "Project", {
        projectId: {
            type: DataTypes.INTEGER,
            primaryKey: true,
            allowNull: false,
            field: "Project_ID",
            autoIncrement: true,
        },
        ...
        dateUpload: {
            type: DataTypes.DATE,
            field: "Date_Upload",
            defaultValue: Sequelize.NOW,
        },
    }

    Project.myCustomQuery = async (projectId) => {
       const query = "select * ...";
       const project = await sequelize.query(query);
       
       return project;
    }


    return Project;
};

Please check here for further reference

https://sequelizedocs.fullstackacademy.com/instance-and-class-methods/

Upvotes: 1

Related Questions