破坏JavaScript中的东西

时间:2018-12-24 05:13:57

标签: node.js express mongoose

我有一个帮助器功能,可以在其中创建一个新用户。

helper函数如下所示

const createNewUser = (newUserDetails) => {
    return new Promise((resolve, reject) => {
      new User({
         fullName: newUserDetails.fullName,
         email: newUserDetails.email,
         image: newUserDetails.image,
         gender: newUserDetails.gender,
         age: newUserDetails.age
      }).save().then((response) => {
          resolve(response)
      }).catch((error) => {
          reject("Problem in Creating New User", error)
      })
    })
}

现在,由于某种原因,这里的这段代码对我来说很不整洁

     fullName: newUserDetails.fullName,
     email: newUserDetails.email,
     image: newUserDetails.image,
     gender: newUserDetails.gender,

我在想是否有办法对其进行破坏?或者有人可以帮助您缩短这段代码

大概是这样

const createNewUser = (newUserDetails) => {
    return new Promise((resolve, reject) => {
      new User({newUserDetails
     }).save().then((response) => {
          resolve(response)
      }).catch((error) => {
          reject("Problem in Creating New User", error)
      })
    })
}

不知道上面的代码是否可以工作,但是我注意到上面我已将其简化为一行

new User({newUserDetails

有人可以帮助我重组和减少第一个功能的长度吗?

这是我的猫鼬模式

const mongoose = require('mongoose')

const userSchema = new mongoose.Schema({
    fullName: String,
    email: String,
    passowrd: String, 
    image: String, 
    age: Number, 
    gender: String,
    createdAt: {type: Date, default: Date.now}
}) 


module.exports = mongoose.model('User', userSchema);

1 个答案:

答案 0 :(得分:1)

这对您来说看起来更好吗?

const createNewUser = (newUserDetails) => {
  return new Promise((resolve, reject) => {
    let {fullName, email, image, gender, age} = newUserDetails
    new User({ fullName, email, image, gender, age})
      .save().then((response) => {
        resolve(response)
      }).catch((error) => {
        reject("Problem in Creating New User", error)
      })
  })
}

您也可以在function参数中使用对象分解。即:

const createNewUser = ({fullName, email, image, gender, age}) => { ...