2015-02-07 16 views
11

come posso usare le classi e le interfacce per scrivere modelli e schemi digitati in Typescript usando sicuramentetyped.classi e interfacce per scrivere typed Modelli e schemi di Mongoose in Typescript usando definitivamente creato

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); 

risposta

16

Questo è come faccio questo:

  1. Definire dattiloscritto classe che definirà la nostra logica.
  2. Definire il interfaccia (che nome del documento): questo è il tipo di mongoose interagirà con
  3. 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 :) 
}) 
+0

grazie questo è veramente utile – afaayerhan

+0

Come si fa a trattare con 'id'? Penso che dovrebbe far parte della classe User ma non potresti ereditare da 'mongoose.Document' –

+0

E 'già dichiarato su UserDocument – Manu

Problemi correlati