最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Using OR statement in sequelize where query - Stack Overflow

programmeradmin0浏览0评论

I have some issue using or statement is sequelize. Below is the code I have been able to e 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

I have some issue using or statement is sequelize. Below is the code I have been able to e 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

Share Improve this question asked Aug 29, 2017 at 17:47 dealwapdealwap 7213 gold badges16 silver badges38 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 9

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
  }
]
发布评论

评论列表(0)

  1. 暂无评论