Closed caiya closed 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:
@atzcl nice,学习学习
请教下如果使用mongoose连接,那么model下ts怎么写