How to write a Mongoose model in ES6 / ES2015

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

    I'm not sure why you're attempting to use ES6 classes in this case. mongoose.Schema is a constructor to create new schemas. When you do

    var Blacklist = mongoose.Schema({});
    

    you are creating a new schema using that constructor. The constructor is designed so that behaves exactly like

    var Blacklist = new mongoose.Schema({});
    

    What you're alternative,

    class Blacklist extends mongoose.Schema {
    

    does is create a subclass of the schema class, but you never actually instantiate it anywhere

    You'd need to do

    export default mongoose.model('Blacklist', new Blacklist());
    

    but I wouldn't really recommend it. There's nothing "more ES6y" about what you are doing. The previous code is perfectly reasonable and is the recommended API for Mongoose.

提交回复
热议问题