尝试在Typescript中实现Mongoose模型。对Google的调查只揭示了一种混合方法(结合JS和TS)。在没有JS的情况下,如何以我比较幼稚的方式实现User类呢?
希望能够不带行李的IUserModel。
import {IUser} from './user.ts'; import {Document, Schema, Model} from 'mongoose'; // mixing in a couple of interfaces interface IUserDocument extends IUser, Document {} // mongoose, why oh why '[String]' // TODO: investigate out why mongoose needs its own data types let userSchema: Schema = new Schema({ userName : String, password : String, firstName : String, lastName : String, email : String, activated : Boolean, roles : [String] }); // interface we want to code to? export interface IUserModel extends Model<IUserDocument> {/* any custom methods here */} // stumped here export class User { constructor() {} }
这是我的方法:
export interface IUser extends mongoose.Document { name: string; somethingElse?: number; }; export const UserSchema = new mongoose.Schema({ name: {type:String, required: true}, somethingElse: Number, }); const User = mongoose.model<IUser>('User', UserSchema); export default User;