即使给出了必填字段,猫鼬验证错误也会发生

时间:2019-04-23 16:17:42

标签: javascript mongodb function mongoose

    // Assign unique krypter id
    assignKrypterID = () => 
    {
      let id = Math.floor(Math.random()*(999999-100000)+100000);
      console.log(id);
      Krypter
        .findOne({krypter_id: id.toString()})
        .then(krypter => {
          if (krypter)
            assignKrypterID()
          else
            return id.toString()
        })
        .catch(err => console.log(err))
    }

    const newKrypter = new Krypter({
      handle: req.body.handle,
      password: req.body.password, // plain text
      krypter_id: assignKrypterID()
    });

    // Hashes the plaintext password and saves it
    bcrypt.genSalt(10, (err, salt) => {
      bcrypt.hash(newKrypter.password, salt, (err, hash) => {
        if (err) throw err;
        newKrypter.password = hash; // encrypted password
        newKrypter
          .save()
          .then(krypter => res.json(krypter))
          .catch(err => console.log(err));
      })
    });

我试图在注册过程中使用功能'assignKrypterID()'为每个用户分配一个唯一的6位ID。但是获得了以下错误:

Obtained error

这是我的模式:

const KrypterSchema = new Schema({
  handle: {
    type: String,
    required: true
  },
  password: {
    type: String,
    required: true
  }, 
  krypter_id: {
    type: String,
    required: true
  }
});

不能使用递归来实现吗?还是递归在这里不好?

帮助我如何修改此设置,以查找是否将随机生成的ID分配给对象。

1 个答案:

答案 0 :(得分:1)

apples

相关问题