【问题标题】:TS 2322: typescript and mongoose.model as a return type to a functionTS 2322:typescript 和 mongoose.model 作为函数的返回类型
【发布时间】:2017-09-14 07:10:35
【问题描述】:

打字稿新手。我试图创建一个基于角色的猫鼬模型工厂将返回猫鼬模型。然后,我将在数据访问层 (DAL) 中使用此模型来继续我的业务层。问题是我收到以下错误。 TS2322:类型'typeof(../../model)不可分配给类型'Model。类型 'typeof('../../model') 中缺少属性 'findById'

我错过了明确的演员表吗?

型号代码

import * as mongoose from "mongoose";

let StudentSchema = new mongoose.Schema({
  id:Number,
  username: String,
  email: String,
  sectors: [{
    sectorName:String,
    QP: String
  }]  
}, {
  timestamps: {
  createdAt: 'created_at'
 }
});

export default mongoose.model('StudentNotification', StudentSchema);

**我的模型工厂代码**我在返回的 StudentNotification 代码中得到错误。

import * as mongoose from "mongoose";
import * as StudentNotification from './models/student';

export class ModelFactory {
private userRole:string;
constructor(role:string){
    this.userRole = role;
}

Create():mongoose.Model<mongoose.Document>{
    switch(this.userRole){
        case "Student":{
            return StudentNotification;
            break;
        }
        default :{
            return null;
        }
    }
}
}

【问题讨论】:

    标签: typescript mongoose


    【解决方案1】:

    要导入默认导出,您需要使用以下语法:

    import * as mongoose from "mongoose";
    import StudentNotification from './models/student'; // HERE !
    
    function Create():mongoose.Model<mongoose.Document>{
        switch(this.userRole){
            case "Student":{
                return StudentNotification;
            }
            default :{
                return null;
            }
        }
    }
    

    或者如果你使用 * 语法,那么你必须这样写:

    import StudentNotification from './models/student';
    ... 
          return StudentNotification.default;
    

    【讨论】:

      【解决方案2】:

      您必须将导入语句更改为:

      import StudentNotification from './models/student';
      

      因为当您导出它时,您使用 default 关键字导出它。

      export default mongoose.model('StudentNotification', StudentSchema);
      

      【讨论】:

        猜你喜欢
        • 2022-11-29
        • 2019-01-15
        • 1970-01-01
        • 2022-11-25
        • 1970-01-01
        • 1970-01-01
        • 2020-08-17
        • 2018-09-05
        • 1970-01-01
        相关资源
        最近更新 更多