Include [op.and] in the Sequelize query object

I want to construct my Sequelize query object based on input parameters. It functions well for database keys, as shown in the example below:

let query = {
  where: {
    id: 5
  }
}

if (inputName) {
  query['where']['name'] = {
    name: inputName
  }
}

Model.findAll(query)

Query Result:

query = {
  where: {
    id: 5,
    name: inputName
  }
}

Now, I aim to achieve the same, but with an additional [op.and] in the query:

Intended outcome:

query = {
  where: {
    id: 5,
    name: inputName,
    [op.and]: [
      {
        type1: inputType
      },
      {
        type2: inputType
      }
    ]
  }
}

I have encountered issues with the following approach:

if (inputType) {
  query['where'][op.and] = [
    {
      type1: inputType
    },
    {
      type2: inputType
    }
  ]
}

Any assistance on this matter would be greatly appreciated

Answer №1

Here is a practical demonstration:

import { sequelize } from '../../db';
import { Model, DataTypes, Op } from 'sequelize';

class User extends Model {}
User.init(
  {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true,
      allowNull: false,
    },
    name: DataTypes.STRING,
    type1: DataTypes.STRING,
    type2: DataTypes.STRING,
  },
  { sequelize, tableName: 'users', modelName: 'user' },
);

(async function() {
  try {
    await sequelize.sync({ force: true });
    
    await User.bulkCreate([
      { id: 1, name: 'mike', type1: 'a', type2: 'a' },
      { id: 2, name: 'tobias', type1: 'c', type2: 'd' },
    ]);

    const inputType = 'a';
    const inputName = 'mike';
    const query = { where: { id: 1, name: inputName } };
    if (inputType) {
      query['where'][Op.and] = [{ type1: inputType }, { type2: inputType }];
    }
    const result = await User.findAll(query);
    console.log(result);
  } catch (error) {
    console.log(error);
  } finally {
    await sequelize.close();
  }
})();

The outcome of the execution:

Executing (default): DROP TABLE IF EXISTS "users" CASCADE;
Executing (default): DROP TABLE IF EXISTS "users" CASCADE;
Executing (default): CREATE TABLE IF NOT EXISTS "users" ("id"   SERIAL , "name" VARCHAR(255), "type1" VARCHAR(255), "type2" VARCHAR(255), PRIMARY KEY ("id"));
Executing (default): SELECT i.relname AS name, ix.indisprimary AS primary, ix.indisunique AS unique, ix.indkey AS indkey, array_agg(a.attnum) as column_indexes, array_agg(a.attname) AS column_names, pg_get_indexdef(ix.indexrelid) AS definition FROM pg_class t, pg_class i, pg_index ix, pg_attribute a WHERE t.oid = ix.indrelid AND i.oid = ix.indexrelid AND a.attrelid = t.oid AND t.relkind = 'r' and t.relname = 'users' GROUP BY i.relname, ix.indexrelid, ix.indisprimary, ix.indisunique, ix.indkey ORDER BY i.relname;
Executing (default): INSERT INTO "users" ("id","name","type1","type2") VALUES (1,'mike','a','a'),(2,'tobias','c','d') RETURNING *;
Executing (default): SELECT "id", "name", "type1", "type2" FROM "users" AS "user" WHERE ("user"."type1" = 'a' AND "user"."type2" = 'a') AND "user"."id" = 1 AND "user"."name" = 'mike';
[ user {
    dataValues: { id: 1, name: 'mike', type1: 'a', type2: 'a' },
    _previousDataValues: { id: 1, name: 'mike', type1: 'a', type2: 'a' },
    _changed: {},
    _modelOptions:
     { timestamps: false,
       validate: {},
       freezeTableName: true,
       underscored: false,
       paranoid: false,
       rejectOnEmpty: false,
       whereCollection: [Object],
       schema: null,
       schemaDelimiter: '',
       defaultScope: {},
       scopes: {},
       indexes: [],
       name: [Object],
       omitNull: false,
       sequelize: [Sequelize],
       tableName: 'users',
       hooks: {} },
    _options:
     { isNewRecord: false,
       _schema: null,
       _schemaDelimiter: '',
       raw: true,
       attributes: [Array] },
    isNewRecord: false } ]

Data entries in the database:

node-sequelize-examples=# select * from users;
 id |  name  | type1 | type2
----+--------+-------+-------
  1 | mike   | a     | a
  2 | tobias | c     | d
(2 rows)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error: The fetch request was unsuccessful [NextJS API]

I keep encountering an error - TypeError: fetch failed after waiting for 300 seconds while requesting an optimization server that requires a response time longer than 300 seconds. The request is being sent from the provided API in NextJS. Is there a way ...

The NgRX Effect is malfunctioning

Working on integrating ngrx with Angular. Authentication is successful, but facing issues with product store implementation: Organizing the project using modules: const routes: Routes = [ { path: '', redirectTo: 'home', ...

What is the solution to rectifying the issue with graphql codegen?

Upon running the command "yarn graphql-codegen," an error occurred and I am unsure how to resolve it: % yarn graphql-codegen yarn run v1.22.4 warning package.json: No license field $ /Users/xxx/node_modules/.bin/graphql-codegen ✔ Parse Configuration ⚠ ...

Understanding the behavior of Bootstrap input-groups when containing hidden sub elements

In a scenario where a button and an input field are enclosed within a div with a bootstrap class named input-group, they expand to occupy the entire width of the enclosing element. However, if the button is hidden, the input field unexpectedly contracts to ...

Touched the Force of ngModel

I am looking to make the required fields show in red in the angular material when the "Submit" button is clicked. To achieve this, I need to trigger the input to be marked as touched. <div class="formRow"> ...

What could be the reason behind the material table not populating with data from the source, despite the service returning an array?

Currently, I am utilizing a mean stack in order to craft a bug tracking system. The issue arises when my express.js service returns an array of issues, which I assign to another array that functions as the dataSource for mat-table. However, despite the ar ...

Caution: Ensuring that every child item in a list possesses a distinct "key" prop is crucial when working with React in TypeScript

Encountering this issue in React (TypeScript): Notification: Each child in a list requires a unique "key" prop. Review the render method of MyCollection Below is the implementation of MyCollection: export default function MyCollection(props:any ) { le ...

Tips for converting a "callback pyramid" into a promise-based structure

I'm currently struggling with understanding how to refactor my code to use promises or the Q library effectively. Let's consider a common basic example: I have a test case that imports the same file twice into a MongoDB database and then checks ...

Utilize Boolean operators such as AND, OR, and NOT to locate specific keywords within a text, mirroring the search capabilities

Is it possible to perform Google-style searches in strings using operators like "or", "and" and "not" with regular expressions? For instance, I aim to search for the words "Javascript", "PHP" and "Perl" within a given string in these ways: Javascript an ...

Implementing authorization middleware using Express.js in Ajax

My app has a straightforward authorization middleware that functions flawlessly with regular GET and POST requests. However, when I send a POST request via AJAX, the middleware fails to redirect to a 401 page and instead bypasses it, allowing the data to b ...

Instead of scrolling through the entire window, focus on scrolling within a specific HTML element

I currently have the following elements: #elementA { position: absolute; width: 200%; height: 100%; background: linear-gradient(to right, rgba(100,0,0,0.3), rgba(0,0,250,0.3)); z-index: 250; } #containerofA { position: fixed; ...

TypeError: Unable to find TextEncoder in mongoose and jest when using TypeScript

Currently, I am working on a project using Node 14 along with Express v4.16.3 and Typescript (v4.7.4). Recently, I added Mongoose (v6.5.2) to the project, and while the logic code seems fine, most of the tests executed by Jest (v26.4.2) are failing with th ...

Error: Angular version 15 is unable to locate the module '@env/environment' or its corresponding type declarations

Recently, I developed an Angular 15 application with the environments folder located under src. Here is a snippet from my tsconfig.json file: "baseUrl": "./src", "paths": { "@app/*": [ "app/*" ], "r ...

Determining interface value based on the presence of another optional interface value

I am working with an interface that looks like this: export interface IButton { label: string; withIcon?: boolean; underlined?: boolean; selected?: boolean; iconName?: string; isLink?: boolean; href?: string; onCLick?: () => void; } My question ...

Utilizing Internationalization in Socket.io

I currently utilize the i18n-2 package for Internationalization in my project by implementing it as follows: router.get('/route', function (req, res, next) { res.redirect('/route/?lang=' + req.i18n.getLocale()); }); Now, ...

The immutability of the List in JavaScript and its

I am confused about how the size of an Immutable JS List grows. According to the official documentation example at https://facebook.github.io/immutable-js/docs/#/List/push, pushing something into an immutable js List should automatically increase its size ...

Add an element to the jQuery collection before the last element, not at the end

My challenge lies in utilizing AJAX to post a comment. However, the last comment element features a submit button within it. Consequently, whenever a new item is appended, it appears after the submit button. <div class="commentContainer" > < ...

Create a div element that expands to occupy the remaining space of the screen's height

I am trying to adjust the min-height of content2 to be equal to the screen height minus the height of other divs. In the current HTML/CSS setup provided below, the resulting outcome exceeds the screen height. How can I achieve my desired effect? The foote ...

Click event not functioning in programmatically loaded HTML

I am facing an issue with a JSON file that contains the page content I am trying to load. The link within it appears as follows: <a data-ng-click='foo()'>Bar</a> When I load this page content into the HTML page: <p class="body" ...

Determine the overall price of the items in the shopping cart and automatically show it at the bottom without the need for manual entry

Creating a checkout form that displays the total cost of products, subtotal, GST cost, delivery cost, and overall price. The goal is to calculate the total by adding together the costs of all products with the "price" class (may need ids) at a 15% increase ...