Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node Sequelize find where $like wildcard

Tags:

sequelize.js

I am trying to add a where like clause to a Node Sequelize findAll, to behave like the sql query select * from myData where name like '%Bob%' with the below code

let data: Array<any> = await MyDataSequelizeAccess.findAll({
  where: {
    name: {
      $like: `%Bob%`
    }
  }
});

Which is returning the below error

Invalid value { '$like': '%Bob%' }

How can I perform that type of where wildcard or where like on my sequelize object?

let data: Array<any> = await MyDataSequelizeAccess.findAll({
  where: {
    name: `Bob`
  }
});

This works as expected, but I cannot get the wildcard to work.

updated still no dice - per https://sequelize.readthedocs.io/en/latest/docs/querying/#operators my syntax looks correct

I'm also trying (and failing) to do the same with $not as in

let data: Array<any> = await MyDataSequelizeAccess.findAll({
  where: {
    name: {
      $not: `Bob`
    }
  }
});

and getting the same error as above Invalid value { '$not': '%Bob%' }

like image 283
Joshua Ohana Avatar asked Dec 29 '18 16:12

Joshua Ohana


Video Answer


1 Answers

Express sequelize first import express and defile Op like so:

const Sequelize = require("sequelize");
const Op = Sequelize.Op;

const { search } = await req.body;

The do like so:

const users = await User.findAll({
    where: {
      username: { [Op.like]: `%${search}%` },
    },
    include: [{ model: Tweet, as: "Tweets" }],
    raw: true,
  }).catch(errorHandler);
like image 166
Simon Angatia Avatar answered Sep 23 '22 12:09

Simon Angatia