将Mongoose模型表示为Typescript类

时间:2016-06-22 13:36:17

标签: angularjs node.js mongodb typescript angular

我正在使用TypeScript编写的Angular 2编写一个简单的Web应用程序。 MongoDB是我在Mongoose框架上的数据库,同时在Express框架上的Node服务器上运行。我的MongoDB和Node代码是用vanilla JS编写的。

现在,我为国家创建了一个Mongoose模型,如下所示:

"use strict";
const Schema = require('mongoose').Schema,
      db = require('../../config/database');

let countrySchema = new Schema({
  countryName: { type: String, index : { unique : true } }
});

let Country = db.model('Country', countrySchema);

module.exports = Country;

现在,Country是我想要的对象。在我的应用程序组件中,我有:

import { Component } from '@angular/core';
import { CountryService } from '../services/country.service';
import { Country } from '../models/country.model';

@Component({
  selector: 'my-app',
  templateUrl: 'app/views/app.component.html',
  providers: [ CountryService ]
})

export class AppComponent {
  originCountries: Country[];
  destinationCountries: Country[];
  constructor(private countryService: CountryService) { };

  ngOnInit() {
    this.getCountries();
  }

  getCountries() {
    this.countryService.getCountries()
      .then(countries => {
        this.originCountries = countries;
        this.destinationCountries = countries;
      });
  }
}

了解originCountries和destinationCountries应该如何成为国家/地区的数组?我不能只从Country模型中导入Country(即使它当时在我脑海中响起)。

创建基于Mongoose模型的国家/地区类的最佳方法是什么?

2 个答案:

答案 0 :(得分:4)

您使用类似此ICountry的界面:

export interface ICountry {
  _id: string;
  name: string;
}

您现在可以在猫鼬设置中使用此界面:

import mongoose = require('mongoose');
import { ICountry } from './interfaces';

var _schema: mongoose.Schema = new mongoose.Schema({
  name: { type: String, required: true, index: { unique: true } }
});

type CountryType = ICountry & mongoose.Document;

var _model = mongoose.model <CountryType> ('Country', _schema);

export class Country {

  static getAll(): Promise<Array<ICountry>> {
    return new Promise<ICountry> ((resolve, reject) => {
      _model.find((err, counties) => {
        err ? reject(err) : resolve(counties);
      });
    });
  }
}

路线设置:

var router = express.Router();
router.get('/api/countries', (req, res) => {
      Country.getAll().then(c => {
        return res.json(c);
      });
    });

如果您需要某些方法或直接在服务类中导入接口,请在Angular应用程序中实现它:

import { ICountry } from '../../interfaces';
...
countries: Array<ICountry>

答案 1 :(得分:0)

这就是我在项目中的表现:

在我的架构文件中:

///<reference path="../typings/mongoose/mongoose.d.ts"/>

import * as mongoose from 'mongoose';

var UserSchema = new mongoose.Schema({
    name: String,
    // ...
});

export interface IUser extends mongoose.Document {
    _id: string;
    name: string;
    // ...
}

export interface IUserModel extends mongoose.Model<IUser> { }

export var User: IUserModel = <IUserModel>mongoose.model<IUser>('User', UserSchema);

在服务器端代码中:

import {User, IUser, IUserModel} from '../schemas/user.schema';

// ...

User.findOne({ ... });

在客户端代码中,我现在可以使用IUser接口:

import {IUser} from '../---/schemas/user.schema';

// ...

userCache: Array<IUser>;