How to write a Mongoose model in ES6 / ES2015 How to write a Mongoose model in ES6 / ES2015 mongoose mongoose

How to write a Mongoose model in ES6 / ES2015


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.


Mongoose can natively support es6 classes (since 4.7, and with no transpiler…).

Just write:

const mongoose = require('mongoose')const { Model, Schema } = mongooseconst schema = new Schema({  type: String,  ip: String,  details: String,  reason: String,})class Tenant extends Model {}module.exports = mongoose.model(Tenant, schema, 'tenant');


Why would you want to do it? mongoose.Schema is not expected to be used in this way. It doesn't use inheritance.

mongoose.Schema is a constructor that takes an object as the first parameter both in ES5 and ES6. No need for ES6 classes here.

Thus even with ES6 the proper way is to have:

const Blacklist = mongoose.Schema({  type: String,  ip: String,  details: String,  reason: String,});