【问题标题】:'TypeError: Cannot set property 'create' of undefined'?'TypeError:无法设置未定义的属性'创建'?
【发布时间】:2021-12-19 06:46:13
【问题描述】:

我正在尝试为“用户”对象创建原型方法。当我从字面上将其声明为函数时,“创建”是如何未定义的?

const mongoose = require("mongoose")

const userSchema = new mongoose.Schema({
  username: {
    type: String,
    required: [true, "Field cannot be left blank"],
    unique: [true, "That username is already taken"],
    minlength: [3, "Username must be at least 3 characters"],
    maxlength: [15, "Username cannot exceed 15 characters"],
  },
})

const Doc = new mongoose.model("user", userSchema)

let User = (username) => {
  this.username = username
}

User.prototype.create = function () {
  return new Promise(async (resolve, reject) => {
    try {
      let doc = await new Doc({
        username: this.username,
      })
      resolve(doc)
    } catch (err) {
      reject(err)
    }
  })
}

module.exports = User

【问题讨论】:

    标签: javascript api express mongoose


    【解决方案1】:

    我能够通过将构造函数的箭头函数更改为匿名函数来解决它。我做了一些研究,ES6 不允许构造函数是箭头函数。

    //previous code
    
    let User = (username) => {
      this.username = username
    }
    
    //correct code
    
    let User = function(username) {
      this.username = username
    }
    
    

    【讨论】:

    • 在您的答案中添加更正的代码并标记为正确答案
    猜你喜欢
    • 2015-09-09
    • 2021-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-20
    • 2022-08-16
    相关资源
    最近更新 更多