如何在ES6 / ES2015中编写一个Mongoose模型

我想在ES6中写下我的mongoose模型。 基本上尽可能地更换module.exports和其他ES5的东西。 这是我的。

 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) 

我在控制台中看到这个错误。

 if (!('pluralization' in schema.options)) schema.options.pluralization = this.options.pluralization; ^ TypeError: Cannot use 'in' operator to search for 'pluralization' in undefined 

我不知道你为什么试图在这种情况下使用ES6类。 mongoose.Schema是创build新模式的构造函数。 当你这样做

 var Blacklist = mongoose.Schema({}); 

您正在使用该构造函数创build一个新的模式。 构造函数的devise与行为完全相同

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

你是另类的,

 class Blacklist extends mongoose.Schema { 

确实是创build模式类的一个子类,但是你永远不会在任何地方实例化它

你需要这样做

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

但我不会推荐它。 关于你在做什么,没有什么“更多的ES6y”。 以前的代码是完全合理的,是Mongoose推荐的API。

你为什么要这样做? mongoose.Schema不会被用于这种方式。 它不使用inheritance。

mongoose.Schema是一个构造函数,它将ES5和ES6中的对象作为第一个参数。 这里不需要ES6课程。

因此,即使使用ES6,正确的方法也是:

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

为了做ES6,类的方式,如问题所述,我只需要在导出的mongoose.model函数中用new调用类。

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

对于那些发现这种search的人来说,原来的问题对我来说似乎相当有效。 我正在使用Babel将ES6 +转换为5.我的自定义mongoose方法在我的调用类中与我的asynchronous/等待代码无法正常工作。 值得注意的是,在我的实例方法中thisnull 。 使用这里提供的解决scheme,我能够得到这个解决scheme,希望可以帮助其他人四处search。

 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)