猫鼬打字稿方式...?

新手上路,请多包涵

尝试在 Typescript 中实现 Mongoose 模型。搜了一下谷歌,只发现了一种混合方式(结合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() {}
}

原文由 Tim McNamara 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 766
2 个回答

这是我的做法:

 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;

原文由 Louay Alakkad 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏