node.js - 如何使用 Mongoose 在 Node js 中将此出生日期转换为年龄

标签 node.js mongodb express mongoose

我正在使用 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、byyear)中获取年龄?

最佳答案

您可以使用提供的数据创建一个新的 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 ) ),因为您的初始值为字符串。

关于node.js - 如何使用 Mongoose 在 Node js 中将此出生日期转换为年龄,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53684596/

相关文章:

node.js - TypeScript 不会解析外部模块 (node.js)

node.js - 在 centos6 上配置 gcc-4.8.5 以包含 GLIBCXX_3.4.20

javascript - `axios.post()` 之后更新状态

node.js - Express 4.0.0 生成已弃用的依赖项和漏洞

javascript - 如何向正确的 GET 路由提交两个 Mongoose 查找查询?

MySql get_lock 用于并发安全更新插入

node.js - Sequelize 验证抛出 [object object] 错误

node.js - MongoDB/mongoose 在两个模型之间创建关系?

java - MongoDB Java 驱动程序 Jackson Mapper MongoJack

node.js - Node/巴别塔 : Switching from babel-node or babel-register to babel-cli for production