代码之家  ›  专栏  ›  技术社区  ›  Rashomon

无法在ES6 Mongoose扩展模型中调用save()。

  •  2
  • Rashomon  · 技术社区  · 6 年前

    我尝试使用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)
      }
    })()
    

    即时通讯: Nodejs 7.10 猫鼬5.3.15

    1 回复  |  直到 6 年前
        1
  •  0
  •   kockburn    6 年前

    这是正常现象。您正在尝试访问 non static 方法从 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();