如何在ES6 / ES2015中编写猫鼬模型 [英] How to write a Mongoose model in ES6 / ES2015
问题描述
我想在ES6中编写我的猫鼬模型。基本上尽可能替换 module.exports
和其他ES5。这就是我所拥有的。
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
$ b $中搜索复数 b
推荐答案
我不确定在这种情况下为什么要尝试使用ES6类。 mongoose.Schema
是用于创建新架构的构造函数。
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({});
您的替代选择,
class Blacklist extends mongoose.Schema {
是创建子类模式类,但您实际上从未在任何地方实例化它
does is create a subclass of the schema class, but you never actually instantiate it anywhere
您需要这样做
export default mongoose.model('Blacklist', new Blacklist());
但我并不是很推荐。您所做的没有任何更多ES6y。前面的代码非常合理,是猫鼬的推荐API。
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.
这篇关于如何在ES6 / ES2015中编写猫鼬模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!