【问题标题】:Cannot call save() in ES6 mongoose extended model无法在 ES6 mongoose 扩展模型中调用 save()
【发布时间】:2019-05-10 01:38:18
【问题描述】:

我正在尝试使用 ES6 语法扩展 Mongoose 模型。虽然我可以成功调用 find({}) 从 mongo 数据库中检索数据,但我无法调用 save() 来保存数据。两者都在模型内部执行。

返回的错误是Error: TypeError: this.save is not a function

const mongoose = require('mongoose')
const {Schema, Model} = mongoose

const PersonSchema = new Schema(
  {
    name: { type: String, required: true, maxlength: 1000 }
  },
  { timestamps: { createdAt: 'created_at', updatedAt: 'update_at' } }
)

class PersonClass extends Model {
  static getAll() {
    return this.find({})
  }
  static insert(name) {
    this.name = 'testName'
    return this.save()
  }
}

PersonSchema.loadClass(PersonClass);
let Person = mongoose.model('Persons', PersonSchema); // is this even necessary?

(async () => {
  try {
    let result = await Person.getAll() // Works!
    console.log(result)
    let result2 = await Person.insert() // FAILS
    console.log(result2)
  } catch (err) {
    throw new Error(err)
  }
})()

我正在使用: 节点 7.10 猫鼬 5.3.15

【问题讨论】:

    标签: javascript node.js class mongoose ecmascript-6


    【解决方案1】:

    这是正常的。您正在尝试从 static 方法访问 non static 方法。

    你需要做这样的事情:

    static insert(name) {
        const instance = new this();
        instance.name = 'testName'
        return instance.save()
    }
    

    一些工作示例:

    class Model {
      save(){
        console.log("saving...");
        return this;
      }
    }
    
    
    class SomeModel extends Model {
    
      static insert(name){
        const instance = new this();
        instance.name = name;
        return instance.save();
      }
    
    }
    
    const res = SomeModel.insert("some name");
    console.log(res.name);

    下面是一个有效和无效的示例。

    class SomeParentClass {
      static saveStatic(){
         console.log("static saving...");
      }
      
      save(){
        console.log("saving...");
      }
    }
    
    class SomeClass extends SomeParentClass {
      static funcStatic(){
        this.saveStatic();
      }
      
      func(){
        this.save();
      }
      
      static funcStaticFail(){
        this.save();
      }
    }
    
    //works
    SomeClass.funcStatic();
    
    //works
    const sc = new SomeClass();
    sc.func();
    
    //fails.. this is what you're trying to do.
    SomeClass.funcStaticFail();

    【讨论】:

    • 非常感谢!解释得很好:)
    猜你喜欢
    • 2019-12-17
    • 1970-01-01
    • 1970-01-01
    • 2020-08-01
    • 2020-01-27
    • 2017-07-27
    • 2020-02-24
    相关资源
    最近更新 更多