【问题标题】:chain static methods in mongoose doesn't work猫鼬中的链式静态方法不起作用
【发布时间】:2018-10-28 14:32:09
【问题描述】:

我在 es6 中尝试了静态方法,知道为什么我不能像下面这样链接我的静态方法吗?甚至可以链接 2 个静态方法吗?

//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)
  }
}

猫鼬模式中的静态和非静态方法有什么区别?我很困惑,因为文档只显示代码示例。我觉得这是多余的,因为它没有显示两个 http://mongoosejs.com/docs/advanced_schemas.html 之间的区别

【问题讨论】:

    标签: javascript node.js mongodb mongoose


    【解决方案1】:

    静态方法中的this是指类函数本身,因为它定义为类的方法。

    class NameClass {
      static async findAll() {
        return this.find({})
      }
    }
    

    等于:

    class NameClass {}
    NameClass.findAll = async function() {
      return this.find({})
    }
    

    MDN Classes

    【讨论】:

    • 所以我应该返回 NameModel,find({}) 而不是 this.find({}) 以便进行“链接”?
    • Noop,因为异步函数返回一个promise,所以NameModel.findAll()返回一个native promise实例。试试const query = await NameModel.findAll(); const response = query.sort('-name')
    • query 已经是响应对象,它没有sort 的方法。
    • @Melissa92 你说得对,我对 Mongoose 不是很熟悉,但是在阅读了一些文档之后,也许我们可以更改 findAll 静态方法的返回值。 static async findAll() { return () => this.find({}) },然后是 const query = await NameModel.findAll(); const response = query().sort('-name')。希望能有所帮助。
    • 哦,好的,返回整个函数,稍后再试。
    猜你喜欢
    • 2016-12-27
    • 2016-08-28
    • 2014-07-15
    • 2016-05-04
    • 2020-09-11
    • 2018-04-10
    • 2017-02-04
    • 1970-01-01
    • 2017-05-05
    相关资源
    最近更新 更多