Javascript 无法在ES6 mongoose扩展模型中调用save()
我正在尝试使用ES6语法扩展Mongoose模型。虽然我可以成功调用Javascript 无法在ES6 mongoose扩展模型中调用save(),javascript,node.js,class,mongoose,ecmascript-6,Javascript,Node.js,Class,Mongoose,Ecmascript 6,我正在尝试使用ES6语法扩展Mongoose模型。虽然我可以成功调用find({})从mongo数据库检索数据,但我无法调用save()保存数据。两者都在模型内部执行 返回的错误为error:TypeError:this.save不是函数 const mongoose = require('mongoose') const {Schema, Model} = mongoose const PersonSchema = new Schema( { name: { type: Stri
find({})
从mongo数据库检索数据,但我无法调用save()
保存数据。两者都在模型内部执行
返回的错误为error:TypeError:this.save不是函数
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)
}
})()
即时通讯使用:
nodejs7.10
猫鼬5.3.15这是正常的。您正试图从
静态
方法访问非静态
方法
您需要这样做:
static insert(name) {
const instance = new this();
instance.name = 'testName'
return instance.save()
}
一些工作示例:
类模型{
保存(){
console.log(“保存…”);
归还这个;
}
}
类SomeModel扩展了模型{
静态插入(名称){
const instance=newthis();
instance.name=名称;
返回instance.save();
}
}
const res=SomeModel.insert(“某些名称”);
console.log(res.name)代码>非常感谢!解释得很好:)