有什么方法可以改善此代码?使用ES6风格,我正在使用最新的稳定版本的node.js。
const UserSchema = new mongoose.Schema({
date: string;
dateObj: {
year: number,
month: number,
day: number
};
project: string;
task: string;
hours: number;
});
let data = new Data();
data.date = new Date(body.date);
data.dateObj = {
year: body.dateObj.year,
month: body.dateObj.month,
day: body.dateObj.day
}
data.project = body.project;
data.task = body.task;
data.hours = body.hours;
}
答案 0 :(得分:0)
考虑到Data
是猫鼬模型,可以从对象中选取属性,并通过构造函数document
argument将其分配给模型实例:
const date = new Date(body.date);
const { year, month, day } = body.dateObj;
const { project, task, hours } = body;
let data = new Data({
date,
dateObj: { year, month, day },
project, task, hours
});
可能不需要选择body.dateObj
属性。
答案 1 :(得分:0)
您可以使用es6结构的组合,例如解构和传播。看看下面的代码片段。
let data = new Data();
const {date, dateObj, project, task, hours} = body;
data = {
date: new Date(date),
dateObj: {...dateObj},
project,
task,
hours
}
答案 2 :(得分:-1)
let data = Object.assign({},
{ dateObj:{
year: body.dateObj.year,
month: body.dateObj.month,
day: body.dateObj.day
},
project: body.project,
task: body.task,
hours: body.hours,
new Data()
})
您可以使用object.assign