【发布时间】:2018-12-11 09:34:08
【问题描述】:
我们有 3 个值,分别是birthdaybirthmonth 和birthyear,因为在前端每个输入都是独立的。在我使用 node js 的后端,我们希望从这 3 个细节中获取年龄。我们在这里找到了 moment js 的这种用法:moment().diff(moment('20170507', 'YYYYMMDD'), 'years')
但是我的代码使用这样的结果有点不同。
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()
});
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([year, month - 1, day]), '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' });
});
});
},
对于上述特殊情况,我们如何使用 moment 将这 3 个值转换为年龄?
【问题讨论】: