How to write a Mongoose model in ES6 / ES2015

前端 未结 7 1921
自闭症患者
自闭症患者 2021-02-18 23:55

I want to write my mongoose model in ES6. Basically replace module.exports and other ES5 things wherever possible. Here is what I have.

import mongo         


        
7条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-19 00:18

    This might be late to reply still, this may help someone who looking for this.

    With ES6 Classes Schemas have a loadClass() method that you can use to create a Mongoose schema from an ES6 class:

    • ES6 class methods become Mongoose methods
    • ES6 class statics become Mongoose statics
    • ES6 getters and setters become Mongoose virtuals

    Here's an example of using loadClass() to create a schema from an ES6 class:

    class MyClass {
      myMethod() { return 42; }
      static myStatic() { return 42; }
      get myVirtual() { return 42; }
    }
    
    const schema = new mongoose.Schema();
    schema.loadClass(MyClass);
    
    console.log(schema.methods); // { myMethod: [Function: myMethod] }
    console.log(schema.statics); // { myStatic: [Function: myStatic] }
    console.log(schema.virtuals); // { myVirtual: VirtualType { ... } }
    

    Reference: this is a sample code from mongoose documentation, for more details mongoose doc

提交回复
热议问题