Search code examples
node.jsoraclesequelize.js

Sequelize use find where field is a CLOB


I use Sequelize with Express for my web API project. I have an Oracle DB.

My current model is look like this

const { DataTypes } = require('sequelize');
const DatabaseModule = require('../modules/database.module');
const PortalModel = require('./portal.model');
const ModuleTypeModel = require('./module_type.model');

const constructor = {
    ID: {
        type: DataTypes.STRING,
        primaryKey: true,
    },
    TITLE: {
        type: DataTypes.STRING,
        allowNull: false
    },
    DESCRIPTION: {
        type: DataTypes.TEXT,
        allowNull: false
    },
    PORTAL_ID: {
        type: DataTypes.STRING,
        allowNull: false,
        references: {
            model: PortalModel,
            key: 'ID'
        }
    },
    BACKGROUND_COLOR: {
        type: DataTypes.STRING,
        allowNull: false
    },
    MODULE_TYPE_ID: {
        type: DataTypes.STRING,
        allowNull: false,
        references: {
            model: ModuleTypeModel,
            key: 'ID'
        }
    },
    POSITION: {
        type: DataTypes.INTEGER,
        allowNull: false
    }
}

const Module = DatabaseModule.define('MODULES', constructor, {
    tableName: 'MODULES',
    timestamps: false,
    createdAt: false,
    updatedAt: false
});

Module.belongsTo(PortalModel, { foreignKey: 'PORTAL_ID'});
Module.belongsTo(ModuleTypeModel, { foreignKey: 'MODULE_TYPE_ID'});
Module.addScope('references', {include: [{model: PortalModel}, {model: ModuleTypeModel}]});

Module.constructor = constructor;

DatabaseModule.sync();

module.exports = Module;

In my service, I call the FindAll function with a where :

/**
 * Return list of all modules
 * @returns {ModuleModel[]} 
 */
exports.getModules = async (description) => {
    const modules = await ModuleModel.findAll({where: {DESCRIPTION: description}});
    return modules;
}

when I try to retrieve data, it return me this :

DatabaseError [SequelizeDatabaseError]: ORA-00932: inconsistent datatypes: expected - got CLOB

So my question is: how to use Sequelize find when the field wanted is a TEXT (CLOB) ?


Solution

  • Since the datatype for DataTypes.TEXT is translated to CLOB, you can't directly use where: {<columnName>: value}.
    You can use Sequelize.Op.like operator:
    Example:

    // import Sequelize.Op
    exports.getModules = async (description) => {
        const modules = await ModuleModel.findAll({where: {DESCRIPTION: { [Op.like]: description}}});
        return modules;
    }
    

    The other way would be using the raw query:

    const modules = await DatabaseModule.query(`SELECT * FROM "MODULES" WHERE dbms_lob.compare(DESCRIPTION, to_clob(<description_character>)) = 0`);