Reputation:
I tried static methods in es6, any clue why I can't chain my static method like below? Is it even possible to chain 2 static methods?
//nameModel.js
const schema = new mongoose.Schema({ name: String })
class NameClass {
static async findAll() {
return this.find({})
}
}
schema.loadClass(NameClass)
export const model = initModel('NameSchema', schema)
//controller.js
import { model as NameModel } from '../models/nameModel'
export default () => async (req, res) {
try {
const test = await NameModel.findAll()
console.log('test', test) //have all the records
const response = await NameModel.findAll().sort('-name') // NameMode.sort is not a function
} catch (e) {
console.log(e)
}
}
What is the diffrence between static and non static method in mongoose schema? I'm confused as the doc only show code sample. I felt it's redundant as it doesn't show difference between two http://mongoosejs.com/docs/advanced_schemas.html
Upvotes: 1
Views: 429
Reputation: 2986
this
in static method is refer to class function itself, since it defined as a method of a class.
class NameClass {
static async findAll() {
return this.find({})
}
}
is equal to:
class NameClass {}
NameClass.findAll = async function() {
return this.find({})
}
see MDN Classes
Upvotes: 1