代码之家  ›  专栏  ›  技术社区  ›  stkvtflw

如何在mongoose对象上打字?

  •  0
  • stkvtflw  · 技术社区  · 4 年前

    正确的打字方法是什么 .toObject()

    const userDoc = await UsersModel.findOne({email})
    const user:IUserObject = userDoc.toObject()
    

    这个 user 不是 IUserObject Pick<Pick<_LeanDocument<IUserModel>, "_id"... .

    这是我的模型输入:

    import {Schema, model, Document} from 'mongoose'
    
    export interface IUser {
      email: string
      password: string
    }
    
    export interface IUserObject extends IUser {
      _id: string
    }
    
    export interface IUserModel extends Document, IUser {}
    
    const schema = new Schema({
      email: { type: String, required: true },
      password: { type: String, required: true }
    })
    
    export const UsersModel = model<IUserModel>('Users', schema)
    
    0 回复  |  直到 4 年前
        1
  •  2
  •   artur grzesiak    4 年前

    猫鼬原型机 doc.toObject() 看起来很复杂,很可能是在条件类型和 infer 接线员。更糟糕的是,它似乎是运行时值的不正确表示,根据 mongoose docs 应该只是POJO:

    type ToObjectReturnType = ReturnType<Document<IUser>['toObject']>
    /*
      ToObjectReturnType = {
        _id?: IUser;
        __v?: number;
        id?: any;
      }
    */
    

    在不修复mongoose中的底层问题的情况下,一个可能的解决方案/改进是使用一个辅助函数从文档中推断底层模型并调用 doc.toObject :

    // a generic method for infering underlying Model out of a mongoose Document
    // and interecting it with { _id: string }
    const docToObject = <D extends Document<any>>(doc: D) =>
      doc.toObject() as D extends Document<infer Model>
        ? Model & { _id: string } // not sure if _id is always there - please modify to your needs / real runtime value
        : never;
    
    // example of usage
    const findUserByEmail = async (email: string) => {
      const userDoc = await UsersModel.findOne({ email });
      return docToObject(userDoc);
    };
    

    STACKBLITZ

    请注意-根据 猫鼬文件 -可以配置 .toObject

        2
  •  0
  •   Mohammad Yaser Ahmadi    4 年前

    const user:IUserObject = JSON.stringify(userDoc)