【问题标题】:How to fix this issue with undefined variable Node js?如何使用未定义的变量 Node js 解决此问题?
【发布时间】:2018-12-12 09:45:21
【问题描述】:

我们正在尝试将这 3 个生日、出生月份和出生年份变量转换为年龄。我们从前端获取这 3 个值,并希望将它们转换为 node js 后端中的年龄并存储在用户数据库中。我们使用 moment js 将其转换为年龄。

module.exports = {
  async CreateUser(req, res) {
    const schema = Joi.object().keys({
      username: Joi.string()
        .required(),
      email: Joi.string()
        .email()
        .required(),
      password: Joi.string()
        .required(),
        birthday: Joi.number().integer()
        .required().min(2).max(2),
        birthmonth: Joi.number().integer()
        .required().min(2).max(2),
        birthyear: Joi.number().integer()
        .required(),
        age:age 
    });

    const { error, value } = Joi.validate(req.body, schema);
    if (error && error.details) {
      return res.status(HttpStatus.BAD_REQUEST).json({ msg: error.details })
    }

    const userEmail = await User.findOne({
      email: Helpers.lowerCase(req.body.email)
    });
    if (userEmail) {
      return res
        .status(HttpStatus.CONFLICT)
        .json({ message: 'Email already exist' });
    }

    const userName = await User.findOne({
      username: Helpers.firstUpper(req.body.username)
    });
    if (userName) {
      return res
        .status(HttpStatus.CONFLICT)
        .json({ message: 'Username already exist' });
    }

    return bcrypt.hash(value.password, 10, (err, hash) => {
      if (err) {
        return res
          .status(HttpStatus.BAD_REQUEST)
          .json({ message: 'Error hashing password' });
      }
     const age = moment().diff(moment([birthyear, birthmonth - 1, birthday]), 'years');

      const body = {
        username: Helpers.firstUpper(value.username),
        email: Helpers.lowerCase(value.email),
        birthday: (value.bday),
         birthmonth: (value.month),
       birthyear: (value.month),
        password: hash,
       age:age
      };
      User.create(body)
        .then(user => {
          const token = jwt.sign({ data: user }, dbConfig.secret, {
            expiresIn: '5h'
          });
          res.cookie('auth', token);
          res
            .status(HttpStatus.CREATED)
            .json({ message: 'User created successfully', user, token });
        })
        .catch(err => {
          res
            .status(HttpStatus.INTERNAL_SERVER_ERROR)
            .json({ message: 'Error occured' });
        });
    });
  },

当我在命令提示符的前端提交注册按钮时出现错误,它显示出生年份未定义并显示在此行下:

const age = moment().diff(moment([birthyear, birthmonth - 1, birthday]),

我放在身体上方并插入年龄:身体内的年龄

我确信其他 2 个值也会发生相同的错误。怎么了?我们该如何解决这个问题?

【问题讨论】:

    标签: node.js express momentjs


    【解决方案1】:

    您从未在您提供的代码中的任何位置定义变量 birthyearbirthmonthbirthmonth,因此该错误是有道理的。

    我不熟悉您正在使用的Joi 对象验证库,但看到value.password 包含上面bcrypt 调用中的密码,我认为您可以将这些字段作为value 上的属性访问。试试这个:

     const age = moment().diff(moment([value.birthyear, value.birthmonth - 1, value.birthday]), 'years');
    

    您可能会在 const body = {...} 代码块中遇到类似的错误,因为您使用的属性名称与架构定义中的不同,因此请仔细检查所有 value.* 行以修复这些错误。

    【讨论】:

    • 感谢您的回复。在身体对象年龄方面:年龄是正确的(最后在身体对象)?
    • @NewTechLover 您可能必须将其更改为age: age.toDate(),因为它当前是您的数据库可能无法理解的moment 日期对象。 toDate 会将其转换为应该可以工作的常规 js Date 对象(尽管这取决于您使用的数据库和数据库库)
    • 我正在使用 mongo DB mongoose
    • @NewTechLover Mongoose 可以很好地与时刻的.toDate() 配合使用
    猜你喜欢
    • 2020-01-19
    • 1970-01-01
    • 1970-01-01
    • 2018-10-08
    • 1970-01-01
    • 2020-10-22
    • 1970-01-01
    • 2021-04-07
    • 1970-01-01
    相关资源
    最近更新 更多