简体   繁体   English

如何改进Node.js中的分配代码(ES6样式)

[英]How to Improve Assignment Code in Node.js (ES6 style)

Is there any way to improve this code? 有什么办法可以改善此代码? Using ES6 style i am using latest stable version of node.js. 使用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;
}

Considering that Data is Mongoose model, properties can be picked from an object and assigned to model instance through constructor document argument : 考虑到Data是猫鼬模型,可以从对象中选取属性,并通过构造函数document参数将其分配给模型实例:

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 
});

Picking body.dateObj properties may be unnecessary. 选择body.dateObj属性可能是不必要的。

You can use combination of es6 constructs like destructuring and spread. 您可以使用es6结构的组合,例如解构和传播。 Take a look at following snippet. 看看下面的代码片段。

let data = new Data();
const {date, dateObj, project, task, hours} = body;
data = {
    date: new Date(date),
    dateObj: {...dateObj},
    project,
    task,
    hours
}
    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() 
    })

You can use object.assign 您可以使用object.assign

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM