atzcl / z

基于 MidwayJS(EggJS) + TypeScript 的多模块应用 [ NodeJS 版 ]
129 stars 20 forks source link

请教下如果使用mongoose连接,那么model下ts怎么写 #1

Closed caiya closed 6 years ago

caiya commented 6 years ago

请教下如果使用mongoose连接,那么model下ts怎么写

atzcl commented 6 years ago

我还没在 NodeJS 中使用过 mongoose,不过去看了下文档跟 @types/mongoose.d.ts ,得出粗略的写法是这样:

// app/model/user.ts

import { Application } from 'egg';

export default function Users (app: Application) {
  const mongoose = app.mongoose;
  const Schema = mongoose.Schema;
  const ObjectId = Schema.Types.ObjectId;

  const modelSchema = new Schema({
    author_id: { type: ObjectId },
    create_at: { type: Date, default: Date.now },
  });

  modelSchema.index({ create_at: -1 });

  return mongoose.model('Users', modelSchema);
}
// app/model/index.d.ts

import { Mongoose, DocumentQuery } from 'mongoose'
import Users from './user'

declare module 'egg' {
  interface Application {
    mongoose: Mongoose
  }

  interface Context {
    model: {
      User: DocumentQuery<Users, {}>;
    }
  }
}
// app/controller/home.ts

import { Controller } from 'egg';

export default class HomeController extends Controller {
  public async index() {
    this.ctx.model.User.find({});
  }
}

仅做参考 :smiley:

caiya commented 6 years ago

@atzcl nice,学习学习