Mongoose the Typescript way…?

后端 未结 14 505
遥遥无期
遥遥无期 2020-11-28 19:27

Trying to implement a Mongoose model in Typescript. Scouring the Google has revealed only a hybrid approach (combining JS and TS). How would one go about implementing the

相关标签:
14条回答
  • 2020-11-28 20:25

    With this vscode intellisense works on both

    • User Type User.findOne
    • user instance u1._id

    The Code:

    // imports
    import { ObjectID } from 'mongodb'
    import { Document, model, Schema, SchemaDefinition } from 'mongoose'
    
    import { authSchema, IAuthSchema } from './userAuth'
    
    // the model
    
    export interface IUser {
      _id: ObjectID, // !WARNING: No default value in Schema
      auth: IAuthSchema
    }
    
    // IUser will act like it is a Schema, it is more common to use this
    // For example you can use this type at passport.serialize
    export type IUserSchema = IUser & SchemaDefinition
    // IUser will act like it is a Document
    export type IUserDocument = IUser & Document
    
    export const userSchema = new Schema<IUserSchema>({
      auth: {
        required: true,
        type: authSchema,
      }
    })
    
    export default model<IUserDocument>('user', userSchema)
    
    
    0 讨论(0)
  • 2020-11-28 20:26

    Try ts-mongoose. It uses conditional types to do the mapping.

    import { createSchema, Type, typedModel } from 'ts-mongoose';
    
    const UserSchema = createSchema({
      username: Type.string(),
      email: Type.string(),
    });
    
    const User = typedModel('User', UserSchema);
    
    0 讨论(0)
提交回复
热议问题