node.jssequelize.js

Sequelize OR condition object


By creating object like this

var condition=
{
  where:
  {
     LastName:"Doe",
     FirstName:["John","Jane"],
     Age:{
       gt:18
     }
  }    
}

and pass it in

Student.findAll(condition)
.success(function(students){

})

It could beautifully generate SQL like this

"SELECT * FROM Student WHERE LastName='Doe' AND FirstName in ("John","Jane") AND Age>18"

However, It is all 'AND' condition, how could I generate 'OR' condition by creating a condition object?


Solution

  • Sequelize version 3 & 4 support the format below using $or, but this is not the latest version/latest format; see other answers which use symbols like [Sequelize.db.Op.or] etc introduced in Sequelize version 5:

    where: {
        LastName: "Doe",
        $or: [
            {
                FirstName: 
                {
                    $eq: "John"
                }
            }, 
            {
                FirstName: 
                {
                    $eq: "Jane"
                }
            }, 
            {
                Age: 
                {
                    $gt: 18
                }
            }
        ]
    }
    

    Will generate

    WHERE LastName='Doe' AND (FirstName = 'John' OR FirstName = 'Jane' OR Age > 18)
    

    See the doc: http://docs.sequelizejs.com/en/latest/docs/querying/#where