dealwap
dealwap

Reputation: 671

Using OR statement in sequelize where query

I have some issue using or statement is sequelize. Below is the code I have been able to come up with:

UserExist(req, res) {
const field = req.body.username || req.body.email;
const getFieldName = field === req.body.username ? 'username' : 'email';
return User
  .findOne({ where: {
    $or: [
      {
        email: req.body.email,
        username: req.body.username
      }
    ]
  }
  })
  .then((user) => {
    if (user) {
      res.status(200).send({ message: `${getFieldName} already exist` });
    }
  })
  .catch(() => res.status(404).send({ message: '' }));

}

Instead of executing the OR statment it only selects * from Users

Upvotes: 1

Views: 6921

Answers (1)

Hemant Kumar
Hemant Kumar

Reputation: 476

According to the sequelize documentation

you should give different where conditions as different element of $or array

Please try this:

$or: [
  {
    email: req.body.email
  },
  {
    username: req.body.username
  }
]

Upvotes: 9

Related Questions