[英]classes and interfaces to write typed Models and schemas of Mongoose in Typescript using definitelytyped
我如何使用类和接口在 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);
这就是我这样做的方式:
mongoose
将与之交互的类型在代码中:
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 :)
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.