【问题标题】:Why is MongoDB not saving my user (issues with async/await?) - Express, mongoDB, Oauth为什么 MongoDB 不保存我的用户(async/await 的问题?) - Express、mongoDB、Oauth
【发布时间】:2021-06-15 19:04:45
【问题描述】:

我正在使用 Oauth 来允许我的用户使用他们的 Google 帐户登录。我已经成功创建了一个函数来检查电子邮件是否经过验证,然后根据用户是否已经保存在数据库中,只需将用户发回 - 或者如果用户不存在,则创建一个新用户。

我的控制台显示消息“电子邮件已验证”和“未找到用户”,因此我知道它会进入该部分代码 - 但它不会继续创建新用户。我的怀疑是这与异步等待有关,并且事情可能以错误的顺序发生。任何想法将不胜感激!

app.post("/googlelogin", (req, res) => {
  const { tokenId } = req.body

  client.verifyIdToken({
    idToken: tokenId, 
    audience: 'XXXX' // removed for demo
  })
    .then(async (response) => {
      const { email_verified, name, email } = response.payload
      console.log(response.payload)

      if (email_verified) {
        console.log('email is verified')

        try {
          const user = await User.findOne({ name, email })
            if (user) {
              console.log('User found!')
              return res.json({
                success: true,
                name: user.name,
                email: user.email,
                token: user.token,
                userID: user._id
              })
            } else {
              console.log('User not found!')
              let newUser = await new User({
                name, 
                email
              }).save()

              return res.json({
                success: true,
                name: newUser.name,
                email: newUser.email,
                token: newUser.token,
                userID: newUser._id
              })
            }
        } catch (error) {
            res.status(400).json({
              success: false,
              message: "Something went wrong",
              error
            })
        }
      } else {
          return res.status(400).json({
            success: false,
            error: "Email not verified",
          })
      }

  })
})

【问题讨论】:

  • 将你的异步函数分别写在 then 块中,然后等待它。
  • 你得到了什么 JSON 响应?

标签: mongodb express oauth


【解决方案1】:

已解决。

找到这个帖子并按照提示删除我的收藏,然后它就起作用了!

MongoError: E11000 duplicate key error collection: tracker-db.users index: username_1 dup key: { username: null }"

【讨论】:

    猜你喜欢
    • 2018-05-07
    • 2016-03-01
    • 2021-09-07
    • 2019-05-30
    • 2020-01-06
    • 2019-10-22
    • 2019-03-24
    • 2020-03-25
    • 1970-01-01
    相关资源
    最近更新 更多