node.js - 使用 OR 条件序列化 FindOrCreate 函数

标签 node.js passport.js sequelize.js

我正在尝试使用 NodeJs 和 Sequelize 创建一个登录/注册系统。当我从用户那里获取发布数据时,我想要执行 FindOrCreate 查询,但其中包含 OR。

db.User.findOrCreate({ 
      username : desiredUsername,
      email: emailAddress
    })

这将执行查询:

SELECT * FROM `users` WHERE `users`.`username`='username' AND `users`.`email`='emailaddress' LIMIT 1;

如何将 AND 部分更改为 OR?如果任一陈述正确,我需要停止注册过程。

感谢您的帮助

最佳答案

您应该使用Op.or运算符来检查用户名电子邮件是否存在:

const Op = require('Sequelize').Op

User.findOrCreate({
  where: { [Op.or]: [{username: desiredUsername}, {email: emailAddress}] },
  defaults: {firstName, lastName}
})
.then(arr => {
  // the first element is the user
  const user = arr[0]
  // the second element tells us if the user was newly created
  const wasCreated = arr[1]

  // do something with the user data
}

Sequelize 文档中的语法运算符引用: http://docs.sequelizejs.com/manual/tutorial/querying.html#operators

关于node.js - 使用 OR 条件序列化 FindOrCreate 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22147151/

相关文章:

sql - Sequelize : join two times the same table

node.js - Mongodb 找到最佳匹配

node.js - 客户端必须经过身份验证才能访问此资源。 jira 休息 API

javascript - Sequelize : TypeError: User. hasMany不是函数

node.js - Passport.authenticate() 使用 Promise 而不是自定义回调

javascript - 未知身份验证策略通行证

javascript - 获取嵌套的BelongsToMany关联

node.js - 添加 Node.js 应用程序作为 Apache 别名?

angularjs - 在 Angular Controller 上获取 EJS 数据

node.js - 如何在 node.js 中生成视频缩略图?