问题描述
我将Node js Express与Mongoose一起使用.在前端,有bday bmonth和byear字段用于注册.但是,我想将这些数据转换为年龄,并将其分别作为年龄保存在用户模型的后端.
I am using Node js Express with Mongoose. In the front-end there are bday bmonth and byear fields for registration. However I want to convert that data into age and save it separately in back-end in user model as age.
功能
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)中获取年龄?
I thought that there is a way that can be used function in the model instantly and calculate age from birth date or convert it inside above function but have no idea how to achieve to that result?How to get age from those 3 details (bday, bmonth,byear)?
推荐答案
您可以使用提供的数据创建一个新的Date
对象,并计算年龄:
You can create a new Date
object with the provided data and calculate the age :
/**
* 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 ) )
.
Keep in mind that you might want to do dateFromDayMonthYear( parseInt( day ), parseInt( month ), parseInt( year ) )
, since your initial values are string.
这篇关于如何使用Mongoose在Node JS中将此出生日期转换为年龄的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!