Combining "AND" and "OR" operators within a Sequelize js scope

Dealing with some difficulties regarding the Sequelize JS.

I'm attempting to incorporate the following query into a Sequelize scope.

SELECT *
FROM Projects
WHERE isDeleted IS NOT true
AND ( 
    ( importSource IS NOT null ) AND ( createdAt BETWEEN '2018-01-19' AND '2018-01-29') 
    OR 
    ( importSource IS null ) AND ( createdAt > '2018-01-19' )
)

Currently trying this in my model without success.

scopes: {
  active: {
    where: {
      isDeleted: {
        [Op.not]: true
      },
      [Op.or]: [
        {
          importSource: { [Op.ne]: null },
          createdAt: {
            [Op.between]: [
              new Date(new Date() - 30 * ( 24 * 60 * 60 * 1000)),
              new Date(new Date() - 4 * (24 * 60 * 60 * 1000))
            ],
          }
        },
        {
          importSource: { [Op.eq]: null },
          createdAt: {
            [Op.gt]: new Date(new Date() - 30 * ( 24 * 60 * 60 * 1000)),
          }
        }
      ]
    }
  }
}

No error is shown, just the MySQL code being executed like below:

Executing (default): SELECT `id`, `url`, `title`, `company`, `importSource`, `importSourceId`, `publishedAt`, `createdAt`, `updatedAt` FROM `Projects` AS `Project` WHERE `Project`.`isDeleted` IS NOT true ORDER BY `Project`.`id` DESC LIMIT 5;

Here is the controller method calling the model and scope.

exports.index = (req, res) => {
  const MAX = 50;
  var numberProjects = ((req.query.number) ? req.query.number : MAX);
  numberProjects = ((numberProjects > MAX) ? MAX : numberProjects);

  Project.scope('active').findAll({
    order: [
      ['id', 'DESC']
    ],
    limit: +numberProjects
  })
  .then( projects => {
    res.send( projects );
  })
};

Any assistance would be greatly appreciated.

Answer №1

After seeking help, I finally cracked the solution just 20 minutes later.

Simply changing [Op.or] to $or did the trick for me.

scopes: {
  active: {
    where: {
      isDeleted: { [Op.not]: true },
      $or: [
        {
          importSource: { [Op.ne]: null },
          createdAt: {
            [Op.between]: [
              new Date(new Date() - 30 * (24 * 60 * 60 * 1000)),
              new Date(new Date() - 4 * (24 * 60 * 60 * 1000))
            ],
          }
        },
        {
          importSource: { [Op.eq]: null },
          createdAt: {
            [Op.gt]: new Date(new Date() - 30 * (24 * 60 * 60 * 1000)),
          }
        }
      ]
    }
  }
}

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

Vue alerts and pop-ups will only show once

Utilizing vue ui to create a new project with Babel and Lint, I integrated dependencies vuetify, vuetify-loader, and vue-bootstrap. My goal was to have a simple 'open dialog' button that would reveal a dialog defined in a separate component file. ...

What could be causing the malfunction of material-UI Tabs?

My Material UI Tabs seem to have stopped working after a recent update. I suspect it may be related to the react-tap-event-plugin update I installed. Initially, I thought it was due to tab indexing but even using values like value='a', value=&apo ...

Error with AngularJS: IE not showing dropdown options for MultiSelect

My application features a multiselect dropdown menu that shows a list of countries. While this dropdown functions correctly in Chrome, it displays options differently in IE as shown below: https://i.stack.imgur.com/xhOmV.png I have attempted to adjust th ...

How to adjust the size of the text on a button in jQuery mobile using custom

I am facing an issue with my jQuery mobile buttons that are placed inside a fieldset. Specifically, I need to adjust the font-size of one of the buttons. Despite attempting to add an inline style, it did not have the desired effect. Furthermore, I tried u ...

Using LARAVEL to connect to mariaDB and SQL Server databases with DBF tables

I have just discovered a method to connect FoxPro tables with MariaDB Server by utilizing ENGINE=CONNECT. By using MySQL WorkBench, I am able to perform insertions, updates, and deletions on existing DBF tables. After following the instructions in the tu ...

Errors and warnings caught off guard while running json-server with the --watch flag

I'm having some trouble using json-server in the following way: $ json-server --watch db.json Every time I try to run that command, I encounter errors or warnings depending on the version of json-server that is installed: 1.0.0-alpha.1-1.0.0-alpha.1 ...

Show the data from the chosen array using Vue JS

Just diving into Vue JS and eager to master it through creating a simple note-taking app. The concept is straightforward - a list of all notes (their titles) on the left, and when you click on a note title, the corresponding note text is displayed in a te ...

Adjust padding of elements based on scrolling movements

Currently, I am attempting to adjust the padding of a specific element based on how far down the page the user scrolls. Ideally, as the user scrolls further down the page, the padding will increase, and as they scroll back up, the padding will decrease. H ...

connecting to the database by utilizing the settings specified in the environment variables

Currently, I am in the process of developing an API for my application to retrieve data from my Amazon database. To ensure secure access, I have stored the necessary credentials as environment variables in a custom.sh file located within profile.d on my se ...

Vue.js Issue: Image not properly redirected to backend server

Having an issue with my Vue app connecting to the backend using express. When I attempt to include an image in the request, it doesn't reach the backend properly. Strangely though, if I bypass express and connect directly from the Vue app, everything ...

As you scroll, the top block in each of the three columns will remain fixed within its

I need assistance with a problem involving three columns and multiple blocks within each column. Specifically, I want the first block in each column to remain fixed at the top when scrolling. However, once you reach the bottom of each column, the first blo ...

Establish a connection with a particular endpoint using socket.io

I'm currently experimenting with socket.io, transitioning from the default JavaScript socket communication. Here's how I'm connecting in my current code: wsuri = "wss://" + window.location.hostname + ":9000"; sock = new WebSocket(wsuri); ...

What is the best way to show two icons next to each other within a React component?

For my school project, I am working on developing an app and encountering a challenge. I have been trying to display two icons side by side on a screen using React (I've been learning React for 5 months but still consider myself a beginner). However, ...

Issues with the webpack-dev-server and React

I was just reading up on Webpack and the moment came for me to start using it, but I ran into an error. npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6a09180b471e1f1e ...

Troubleshooting the Node.js Server Error Encountered when Enabling AngularJS html5Mode(true)

When using routeProvider and stateProvider in AngularJS with HTML5 mode set to true, everything functions correctly until the page is refreshed. On a Node.js server, I am unsure of what needs to be written on the server side to prevent receiving a "Can no ...

How can JavaScript Regular Expressions be used for Form Validation?

For my registration form, I am including fields such as userid, name, email, password, confirm password, and affiliation. Using regular expressions in JavaScript, I am validating these fields. I am attempting to display any validation errors within the for ...

Sending a large base64-encoded file via Ajax POST using a mobile device

I have a Canvas where clients can sign a form on my website. The base64 string is sent through an AJAX POST to a Node.js server, and it works fine regardless of the file size when I run the process on my computer. If the signature is small, it can also be ...

I encountered a 429 error while trying to make a request to the Spotify API

I recently encountered an issue with my website where I am trying to retrieve and display my playlists. Everything was working fine yesterday, but this morning I started getting error 429 every time I tried to retrieve data from the api, even though I have ...

In the world of HTML, when it comes to deciding between the div and span tags, which

This inquiry may seem repetitive, however I am still not content with the clarification I discovered. I am curious: what potential outcomes would arise if I opt to use a span tag instead of a div tag? Both are non-semantic tags, as I am aware. Typically, ...

What is the best way to loop through all the child elements of a scene in three

Using Three.js: I have a method called removeBysid(id) My goal is to access the unique sid of the third child's treeNode in my scene by traversing through all the children. When I run the following command in the console: scene.children[4].child ...