首页 > 解决方案 > 如何使用 Mongoose 在 Node js 中将此出生日期转换为年龄

问题描述

我正在将 Node js Express 与 Mongoose 一起使用。在前端有 bday bmonth 和 byear 字段用于注册。但是我想将该数据转换为年龄并将其作为年龄单独保存在用户模型的后端。

功能

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

    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 body = {
        username: Helpers.firstUpper(value.username),
        email: Helpers.lowerCase(value.email),
        bday: (value.bday),
         bmonth: (value.month),
       byear: (value.month),
        password: hash
      };
      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' });
        });
    });
  },

模型

username: { type: String },
  email: { type: String },
  password: { type: String },
   bday: { type: String },
  bmonth: { type: String },
  byear: { type: String },
  age: { type: String },

我认为有一种方法可以立即在模型中使用函数并从出生日期计算年龄或将其转换为上述函数但不知道如何实现该结果?如何从这 3 个细节(bday、bmonth、byear)中获取年龄?

标签: node.jsmongodbexpressmongoose

解决方案


Date您可以使用提供的数据创建一个新对象并计算年龄:

/**
 * Date from day / month / year
 *
 * @param day    The day of the date
 * @param month  The month of the date
 * @param year   The year of the date
 */
function dateFromDayMonthYear( day, month, year ) {
    return new Date( year, month - 1, day, 0, 0, 0, 0 );
}

/**
 * Get the years from now
 *
 * @param date  The date to get the years from now
 */
function yearsFromNow( date ) {
    return (new Date() - date) / 1000 / 60 / 60 / 24 / 365;
}

/**
 * Gets the age of a person
 *
 * @param birthDate  The date when the person was born
 */
function age( birthDate ) {
    return Math.floor( yearsFromNow( birthDate ) );
}

console.log( age( dateFromDayMonthYear( 7, 12, 2008 ) ) ); // 10
console.log( age( dateFromDayMonthYear( 17, 12, 2008 ) ) ); // 9

请记住,您可能想要这样做dateFromDayMonthYear( parseInt( day ), parseInt( month ), parseInt( year ) ),因为您的初始值是字符串。


推荐阅读