Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize.op is not defined

I'm using sequelize with Node.js. I'm trying to use Sequelize.op request. But it doesn't work, this is my code :

var Sequelize = require('sequelize');
const Op = Sequelize.Op;
const operatorsAliases = {
$eq: Op.eq
}

This is the error in the node console :

enter image description here

Do you have any idea ?

Thank you

like image 261
Anaïs Saez Avatar asked Oct 05 '17 07:10

Anaïs Saez


People also ask

How do I import op into Sequelize?

When you use the Sequelize ORM for your JavaScript project, the SQL operators are included in the library in the form of the Op object. You need to import the object from Sequelize to use it in your code: const { Sequelize, Op } = require("sequelize");


2 Answers

I found the solution, I updated the sequelize version via npm, and it's work. So the solution is

npm i [email protected] --s

like image 62
Anaïs Saez Avatar answered Sep 16 '22 11:09

Anaïs Saez


Last version for now:

4.22.2

models/user.js:

const Sequelize = require('sequelize');
const op = Sequelize.Op;
const operatorsAliases = {
    $eq: op.eq,
    $or: op.or,
}

module.exports = function(sequelize) {

    var User = sequelize.define('user', {
        id: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true },
        email: { type: Sequelize.STRING },
        username: { type: Sequelize.STRING(120) },
        ...
    });

    User.beforeCreate((user, options) => {
        var where = {
            type: 1,
            deleted: null, 
            // With aliases
            $or: [{email: {$eq: user.email} }, { username: {$eq: user.username}}]
            // Without aliases: Last version
            //[op.or]: [ { email: user.email }, { username: user.username } ]
        };

        return User.findOne({ where: where })
            .then(userFound => {
                ...  
            })
            .catch(err => {
                ...
            });
    });
    ...
    return User;
};
like image 25
alditis Avatar answered Sep 18 '22 11:09

alditis