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