我就是这样做的:
- 定义TypeScript class,它将定义我们的逻辑.
- 定义interface(我将其命名为文档):这是
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 :)
})