使用definitelytyped在类型脚本中编写Mongoose的类型模型和模式的类和接口

时间:2015-02-07 07:39:17

标签: node.js mongodb mongoose typescript passport.js

如何使用类和接口在Typescript中使用absolutetyped编写类型化的模型和模式。

import mongoose = require("mongoose");

 //how can I use a class for the schema and model so I can new up
export interface IUser extends mongoose.Document {
name: String;
}

export class UserSchema{
name: String;
}




var userSchema = new mongoose.Schema({
name: String
});
export var User = mongoose.model<IUser>('user', userSchema);

1 个答案:

答案 0 :(得分:19)

我就是这样做的:

  1. 定义TypeScript ,它将定义我们的逻辑。
  2. 定义界面(我将其命名为Document):mongoose将与
  3. 进行交互的类型
  4. 定义模型(我们将能够查找,插入,更新......)
  5. 在代码中:

    import { Document, Schema, model } from 'mongoose'
    
    // 1) CLASS
    export class User {
      name: string
      mail: string
    
      constructor(data: {
        mail: string
        pass: string
      }) {
        this.mail = data.mail
        this.name = data.name
      }
    
      /* any method would be defined here*/
      foo(): string {
         return this.name.uppercase() // whatever
      }
    }
    
    // no necessary to export the schema (keep it private to the module)
    var schema = new Schema({
      mail: { required: true, type: String },
      name: { required: false, type: String }
    })
    // register each method at schema
    schema.method('foo', User.prototype.foo)
    
    // 2) Document
    export interface UserDocument extends User, Document { }
    
    // 3) MODEL
    export const Users = model<UserDocument>('User', schema)
    

    我将如何使用它?让我们假设代码存储在user.ts中,现在您可以执行以下操作:

    import { User, UserDocument, Users } from 'user'
    
    let myUser = new User({ name: 'a', mail: 'aaa@aaa.com' })
    Users.create(myUser, (err: any, doc: UserDocument) => {
       if (err) { ... }
       console.log(doc._id) // id at DB
       console.log(doc.name) // a
       doc.foo() // works :)
    })