24

I am looking to pull items from a postgres data base with Sequelize, but only return items that have an id that does not equal any items in a given array.

In the Sequelize documentation, there are operators $ne for not equal and $in for returning items that have properties with values that match the given array, but it doesn't look like there is an operator for something that combines those two.

For example, if I were to have items in my database with ids [1, 2, 3, 4, 5, 6], and I wanted to filter those by comparing to another array (ie [2,3,4]), so that it would return items [1, 5, 6]. In my example i also randomize the return order and limit, but that can be disregarded.

function quizQuestions(req, res) {
  const query = {
    limit: 10,
    order: [ [sequelize.fn('RANDOM')] ],
    where: {
      id: { $ne: [1, 2, 3] } // This does not work
    }
  };

  Question.findAll(query)
  .then(results => res.status(200).json(map(results, r => r.dataValues)))
  .catch(err => res.status(500).json(err));
}

Edit: With @piotrbienias answer, my query looks like this:

  const query = {
    limit: 10,
    order: [ [sequelize.fn('RANDOM')] ],
    where: {
      id: { $notIn: [1, 2, 3] }
    }
  };

2 Answers 2

62

using

const Op = Sequelize.Op
where: {
      id: {[Op.notIn]:[1, 2, 3]}
}

See operators:

Sequelize exposes symbol operators that can be used for to create more complex comparisons

Sign up to request clarification or add additional context in comments.

1 Comment

I wonder why they don't make id: { $ne: [1, 2, 3] } work :-( Sounds intuitive given that id: { [1, 2, 3] } works and so $in is never needed anymore. Still doesn't work tested as of 6.14.
12

There exists $notIn, you must have missed it. Exemplary query with $notIn generates

SELECT "id", "name"
FROM "categories" AS "Category"
WHERE "Category"."id" NOT IN (1, 2);

EDIT

The documentation you refer to is for 2.0 version of Sequelize, you should update to 3.0.

1 Comment

Perfect, thanks! I actually didn't notice I was reading the 2.0 docs when I posted. I am using sequelize 3.30.2, thanks for the help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.