【问题标题】:How to write a Mongoose model in ES6 / ES2015如何在 ES6 / ES2015 中编写 Mongoose 模型
【发布时间】:2016-04-06 05:46:46
【问题描述】:

我想在 ES6 中编写我的猫鼬模型。基本上尽可能替换 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

【问题讨论】:

标签: javascript node.js mongoose ecmascript-6


【解决方案1】:

我不确定您为什么在这种情况下尝试使用 ES6 类。 mongoose.Schema 是创建新模式的构造函数。当你这样做时

var Blacklist = mongoose.Schema({});

您正在使用该构造函数创建一个新模式。构造函数的设计使其行为与

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

你有什么选择,

class Blacklist extends mongoose.Schema {

确实是创建模式类的子类,但您从未在任何地方实际实例化它

你需要做的

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

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

【讨论】:

    【解决方案2】:

    Mongoose can natively support es6 classes(从 4.7 开始,并且没有转译器……)。

    只写:

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

    【讨论】:

    • 这不起作用,我抛出了 MissingSchemaError !
    【解决方案3】:

    你为什么要这样做? mongoose.Schema 预计不会以这种方式使用。它不使用继承。

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

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

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

    【讨论】:

      【解决方案4】:

      如问题所述,要以类 ES6 的方式执行操作,我只需在导出的 mongoose.model 函数中调用带有 new 的类。

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

      【讨论】:

        【解决方案5】:

        对于那些发现这个搜索的人来说,最初的问题对我来说似乎很有效。我正在使用 Babel 将 ES6+ 转换为 5。我的自定义 mongoose 方法在调用类中的 async/await 代码中表现不佳。值得注意的是this 在我的实例方法中是null。使用此处提供的解决方案,我能够得出这个解决方案,希望能帮助其他人四处搜索。

        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)
        

        【讨论】:

          【解决方案6】:

          这可能仍然迟到回复,这可能会帮助寻找这个的人。

          对于 ES6 类,Schema 有一个 loadClass() 方法,您可以使用该方法从 ES6 类创建 Mongoose 模式:

          • ES6 类方法变成 Mongoose 方法
          • ES6 类静态变成 Mongoose 静态
          • ES6 getter 和 setter 变成 Mongoose virtuals

          这是一个使用 loadClass() 从 ES6 类创建模式的示例:

          class MyClass {
            myMethod() { return 42; }
            static myStatic() { return 42; }
            get myVirtual() { return 42; }
          }
          
          const schema = new mongoose.Schema();
          schema.loadClass(MyClass);
          
          console.log(schema.methods); // { myMethod: [Function: myMethod] }
          console.log(schema.statics); // { myStatic: [Function: myStatic] }
          console.log(schema.virtuals); // { myVirtual: VirtualType { ... } }
          

          参考:这是来自猫鼬文档的示例代码,更多详细信息mongoose doc

          【讨论】:

            【解决方案7】:

            这将起作用:

            import mongoose from 'mongoose';
            
            const { Schema } = mongoose;
            const userSchema = new Schema({
            
              email: {
                  type: String,
                  required: true
              },
              firstName: {
                  type: String,
              },
              lastName: {
                  type: String
              },
              age: {
                  type: Number
              }
            });
            
            export default mongoose.model('User', userSchema);
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2016-05-03
              • 2015-12-18
              • 2015-03-14
              • 2019-05-10
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多