jabbermonkey
jabbermonkey

Reputation: 1820

Class constructors cannot be invoked without 'new'

Just upgraded to node 4.1.2 and using Mongorito (which uses ES6) to access Mongo and I'm getting this:

Model file:

var Mongorito = require('mongorito');
var Model = Mongorito.Model;
var config = require('../config/config');
Mongorito.connect(config.mongo.url);

class Listing extends Model {}

module.exports = Listing;

And I'm including it:

var Listing = require('../models/listing');
var listing = yield Listing.where('cacheKey', key).findOne();
TypeError: Class constructors cannot be invoked without 'new'
      at Listing.Model (/node_modules/mongorito/lib/mongorito.js:140:15)
      at new Listing (/models/listing.js:7:14)
      at Query.find (/node_modules/mongorito/lib/query.js:355:21)
      at [object Generator].next (native)
      at onFulfilled (/node_modules/koa/node_modules/co/index.js:65:19)
      at run (/node_modules/babel/node_modules/babel-core/node_modules/core-js/modules/es6.promise.js:89:39)
      at /node_modules/babel/node_modules/babel-core/node_modules/core-js/modules/es6.promise.js:100:28
      at flush (/node_modules/babel/node_modules/babel-core/node_modules/core-js/modules/$.microtask.js:17:13)
      at doNTCallback0 (node.js:408:9)
      at process._tickCallback (node.js:337:13)

Upvotes: 7

Views: 14269

Answers (3)

pomber
pomber

Reputation: 23980

Transpiled classes are causing the problem.
If you are using the env preset, you can exclude the classes plugin like this:

  presets: [
    ["env", { exclude: ["transform-es2015-classes"] }]
  ]

Upvotes: 0

Endel Dreyer
Endel Dreyer

Reputation: 1654

It turns out that if you use es2015 preset on the library side allows the user to extend classes defined on them.

.babelrc:

{
  "presets": ["es2015"]
}

I didn't tested on mongorito, but I was having the same problem extending a 3rd party class and using this preset solved for me.

Upvotes: 1

loganfsmyth
loganfsmyth

Reputation: 161457

This is because Babel's transpiled ES6 classes cannot be used to extend a real ES6 class. If you want to use mongorito, you would have to blacklist Babel's es6.classes transform so that your Listing class was also a native ES6 class.

Upvotes: 18

Related Questions