Questo è come faccio questo:
- Definire dattiloscritto classe che definirà la nostra logica.
- Definire il interfaccia (che nome del documento): questo è il tipo di
mongoose
interagirà con
- definire il modello (saremo in grado di trovare, inserire, aggiornare ...)
in codice:
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)
Come dovrei usare questo? immaginiamo che il codice è memorizzato in user.ts
, ora saresti in grado di effettuare le seguenti operazioni:
import { User, UserDocument, Users } from 'user'
let myUser = new User({ name: 'a', mail: '[email protected]' })
Users.create(myUser, (err: any, doc: UserDocument) => {
if (err) { ... }
console.log(doc._id) // id at DB
console.log(doc.name) // a
doc.foo() // works :)
})
grazie questo è veramente utile – afaayerhan
Come si fa a trattare con 'id'? Penso che dovrebbe far parte della classe User ma non potresti ereditare da 'mongoose.Document' –
E 'già dichiarato su UserDocument – Manu