mysqlsqlsequelize.js

Sequelize - Custom Operators


I'm interested in adding a couple custom operators to our usage of the Sequelize ORM. Specifically I want to add on operators that mimic the startswith and endswith lookup operators that Django has implemented. Looking through the internals on Sequelize, I can't seem to find the place where it would be to inject this kind of logic. In short, the functionality I'd like to implement is something like:

{
    stringField: {
        [Op.startsWith]: 'bl'
    }
}

to produce the desired sql of

WHERE stringField LIKE 'bl%'

I know that in the documentation all the examples show manually appending the % symbol but for my purposes I want to be able to dynamically wrap the value based on the operator being used.


Solution

  • You should be able to do this with the current version of sequelize,

    Post.findAll(
      {
        where: {
          someAttribute: {
           $startsWith: 'my name' // or from the request body field value
         }
        }
      }
    )
    

    This can be found from the sequelize docs here for more operators. sequelize operators

    Otherwise you can replace the $startsWith with the old version to suit your needs,

    [Op.startsWith] : "field value"