注册不起作用并引发参数错误

时间:2019-01-27 19:24:18

标签: mongodb express mongoose

我目前可以使用以前创建的用户凭据登录,并且可以正常使用该应用程序,但是无法创建新用户。我在客户端使用React.js,在后端使用Express api。我收到猫鼬验证错误。所有身份验证均随课程使用的模板一起提供,而我没有涉及任何这些文件。我什至回去比较提交历史树,以确保没有任何更改。

这是我的用户架构和注册路线。我试图从模型中消除唯一性,但这并没有影响它。我知道可能存在很多潜在问题,但是如果有人对潜在问题有任何建议,我将永远感激不已!我在控制台中登录并记录了req.body.credentials,并且发送过来的数据看起来不错。

错误代码:422无法处理的实体 服务器端错误:“收到的参数未通过Mongoose验证”

const mongoose = require('mongoose')
const { petSchema } = require('./pet.js')
const { pictureSchema } = require('./picture.js')

const userSchema = new mongoose.Schema({
  email: {
    type: String,
    required: true,
    unique: true
  },
  hashedPassword: {
    type: String,
    required: true
  },
  token: String,
  pets: [petSchema],
  pictures: [pictureSchema]
}, {
  timestamps: true,
  toObject: {
    // remove `hashedPassword` field when we call `.toObject`
    transform: (_doc, user) => {
      delete user.hashedPassword
      return user
    }
  }
})

module.exports = mongoose.model('User', userSchema)
// SIGN UP
// POST /sign-up
router.post('/sign-up', (req, res) => {
  // start a promise chain, so that any errors will pass to `handle`
  console.log(req.body.credentials)
  Promise.resolve(req.body.credentials)
    // reject any requests where `credentials.password` is not present, or where
    // the password is an empty string
    .then(credentials => {
      if (!credentials ||
          !credentials.password ||
          credentials.password !== credentials.password_confirmation) {
        throw new BadParamsError()
      }
    })
    // generate a hash from the provided password, returning a promise
    .then(() => bcrypt.hash(req.body.credentials.password, bcryptSaltRounds))
    .then(hash => {
      // return necessary params to create a user
      return {
        email: req.body.credentials.email,
        hashedPassword: hash
      }
    })
    // create user with provided email and hashed password
    .then(user => User.create(user))
    // send the new user object back with status 201, but `hashedPassword`
    // won't be sent because of the `transform` in the User model
    .then(user => res.status(201).json({ user: user.toObject() }))
    // pass any errors along to the error handler
    .catch(err => handle(err, res))
})

1 个答案:

答案 0 :(得分:0)

已解决。我在用户中拥有的一个子文档中有一个键,其值设置为unique。我需要消除这种情况,因为我的数据库正在使用空值索引用户并引发重复错误。然后,我需要重置数据库(我只是对其进行了重命名以对其进行测试),以便该配置没有任何保存的索引。我也刚刚在Heroku中删除了我的收藏集(幸运的是,我那里没有大量数据,因此这种解决方案非常适合我的情况)。现在,我可以再次注册用户,而不会出现重复的键错误。