首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >无法在ES6猫鼬扩展模型中调用save()

无法在ES6猫鼬扩展模型中调用save()
EN

Stack Overflow用户
提问于 2018-12-08 15:18:39
回答 1查看 395关注 0票数 2

我试图用ES6语法扩展一个猫鼬模型。虽然我可以调用成功的find({})从mongo数据库中检索数据,但无法调用save()来保存数据。这两种方法都在模型内部执行。

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

代码语言:javascript
复制
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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-12-08 15:35:11

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

你需要这样做:

代码语言:javascript
复制
static insert(name) {
    const instance = new this();
    instance.name = 'testName'
    return instance.save()
}

一些工作实例:

代码语言:javascript
复制
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);

下面是一个例子,说明什么是有效的,哪些是不起作用的。

代码语言:javascript
复制
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();

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53683900

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档