【问题标题】:Representing Mongoose model as a Typescript class将 Mongoose 模型表示为 Typescript 类
【发布时间】:2016-07-04 13:36:27
【问题描述】:

我正在使用用 TypeScript 编写的 Angular 2 编写一个简单的 Web 应用程序。 MongoDB 是我在 Mongoose 框架上运行的数据库,同时在 Express 框架上的节点服务器上运行。我的 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 模型的国家/地区类的最佳方法是什么?

【问题讨论】:

标签: angularjs node.js mongodb typescript angular


【解决方案1】:

你使用像这样的 ICountry 界面:

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

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

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>

【讨论】:

    【解决方案2】:

    这就是我在项目中的做法:

    在我的架构文件中:

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

    【讨论】:

    • 我们的做法几乎相同,但我喜欢将接口与 Document 类分离。
    • 查看@DNRN 的回答!他展示了如何将界面和文档类型组合成一种新类型。
    猜你喜欢
    • 2021-10-17
    • 2019-01-13
    • 1970-01-01
    • 1970-01-01
    • 2019-02-03
    • 2021-06-22
    • 2016-10-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多