How to write a Mongoose model in ES6 / ES2015

前端 未结 7 1965
自闭症患者
自闭症患者 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:02

    For those who find this searching around, the original question seems pretty valid to me. I'm using Babel transpiling ES6+ down to 5. My custom mongoose methods did not play well with my async/await code in my calling class. Notably this was null in my instance methods. Using the solution provided here, I was able to arrive at this solution that hopefully helps others searching around.

    import mongoose from 'mongoose'
    
    class Tenant extends mongoose.Schema {
      constructor() {
        const tenant = super({
          pg_id: Number,
          name: String,
          ...
        })
    
        tenant.methods.getAccountFields = this.getAccountFields
        tenant.methods.getCustomerTypes = this.getCustomerTypes
        tenant.methods.getContactFields = this.getContactFields
        ...
        tenant.methods.getModelFields = this.getModelFields
    
        return tenant
      }
    
      getAccountFields() {
        return this.getModelFields(this.account_fields_mapping)
      }
    
      getCustomerTypes() {
        //code
      }
    
      getContactFields() {
        //code
      }
    
      ...
    
      getModelFields(fields_mapping) {
        //code
      }
    }
    
    export default mongoose.model('Tenant', new Tenant)
    

提交回复
热议问题