node.js - 使用绝对类型在 Typescript 中编写 Mongoose 的类型化模型和模式的类和接口(interface)

标签 node.js mongodb mongoose typescript passport.js

如何使用类和接口(interface)在 Typescript 中使用肯定类型编写类型化模型和模式。

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. 定义 TypeScript class,它将定义我们的逻辑。
  2. 定义 interface(我将其命名为 Document):这是 mongoose 将与之交互的类型
  3. 定义模型(我们将能够查找、插入、更新...)

在代码中:

import { Document, Schema, model } from 'mongoose'

// 1) CLASS
export class User {
  name: string
  mail: string

  constructor(data: {
    mail: string
    name: string
  }) {
    this.mail = data.mail
    this.name = data.name
  }
  
  /* any method would be defined here*/
  foo(): string {
     return this.name.toUpperCase() // 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 :)
})

关于node.js - 使用绝对类型在 Typescript 中编写 Mongoose 的类型化模型和模式的类和接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28379788/

相关文章:

javascript - 使用 Node.js 操作 Mongoose/MongoDB 数组

javascript - 发布http ://localhost:3000/upload 500 (Internal Server Error)

mongodb - 如何使用 mgo 和 Go 查询 MongoDB 的日期范围?

node.js - Mongoose 密码哈希

javascript - Gruntfile.js 任务...错误

mongodb - 如何在 MongoDB 中构建基于字段哈希的分片

java - mongodb DAO 在 save() 之前将所有属性设置为 null

javascript - Mongoose 查询在回调后挂起

node.js - Mongoose - 按字符串查询嵌套文档

mongodb - 在 Mongoose 中搜索嵌入对象