Невозможно вызвать save () в расширенной модели ES6 mongoose - PullRequest
0 голосов
/ 08 декабря 2018

Я пытаюсь расширить модель Mongoose, используя синтаксис ES6.Хотя я могу успешно позвонить find({}) для извлечения данных из базы данных Монго, я не могу вызвать 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 mongoose 5.3.15

1 Ответ

0 голосов
/ 08 декабря 2018

Это нормально.Вы пытаетесь получить доступ к методу 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();
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...