Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a Mongoose model in ES6 / ES2015

Tags:

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 mongoose from 'mongoose'  class Blacklist extends mongoose.Schema {   constructor() {     super({       type: String,       ip: String,       details: String,       reason: String     })   } }  export default mongoose.model('Blacklist', Blacklist) 

I see this error in the console.

if (!('pluralization' in schema.options)) schema.options.pluralization = this.options.pluralization;                                  ^  TypeError: Cannot use 'in' operator to search for 'pluralization' in undefined 
like image 296
Noah Avatar asked Jan 01 '16 21:01

Noah


1 Answers

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.

like image 147
loganfsmyth Avatar answered Oct 21 '22 05:10

loganfsmyth