【问题标题】:Typescript Mongoose: Why are methods of aggregated documents undefinedTypescript Mongoose:为什么聚合文档的方法未定义
【发布时间】:2022-02-09 01:38:33
【问题描述】:

当使用 mongoose 聚合时,它会返回一个 ProfileDocuments 数组。 结果数组中的 Documents 不包含 ProfileDocument 实现的方法。 这导致无法对数据库中的文档调用 checkPassword 等文档方法。

聚合示例

ProfileSchema.statics.findByLogin = async function (login: string) {
  // why do methods of aggregated documents not work?
  const results = await this.aggregate([{
    $match: { 
      $or:[{username: login}, {mail: login}]
    }
  }])

  if (results.length === 0) {
    throw new Error('Profile not found')
  }

  const profile = await this.findById(results[0]._id)

  console.log(results[0].checkPassword)
  console.log(profile.checkPassword)

  return profile
}

控制台输出

undefined
[Function (anonymous)]

方法实现

interface ProfileDocument extends IProfile, Document {
  getDisplayname: () => Promise<string>
}

ProfileSchema.methods.checkPassword = async function (password: string) {
  return await bcrypt.compare(password, this.pass)
}

【问题讨论】:

    标签: typescript mongoose methods model aggregate


    【解决方案1】:

    根据mongoose 文档,

    aggregates 返回的文档是普通的 javascript 对象,而不是 mongoose 文档(因为可以返回任何形状的文档)。

    【讨论】:

    • 感谢您指出这一点!在不进行第二次请求的情况下将它们转换为模型的合适方法是什么?
    • @Grifting 我对 MongoDb 的经验较少。你能试试const resultDocuments = results.map(result=&gt;new ProfileSchema(result));,我想应该把文档形状还给我吗?
    • Takur 很遗憾它没有用。我还尝试按照 API 中的说明制作 Hydrated 文档,但没有成功。
    • @Thakur 我找到了一个解决方案,ProfileSchema 有一个名为 hydrate 的方法,因此 ProfileSchema.hydrate(doc) 或在静态方法 this.hydrate(doc) 的上下文中有效。
    【解决方案2】:

    正如@Thakur 提到的聚合返回原始文档。 Mongoose 提供了一种 hydrate 方法来将方法添加到文档中。

    使用ProfileSchema.hydrate(doc) 或在静态方法this.hydrate(doc) 的上下文中返回ProfileDocuments。

    /**
     * Shortcut for creating a new Document from existing raw data, pre-saved in the DB.
     * The document returned has no paths marked as modified initially.
     */
    hydrate(obj: any): EnforceDocument<T, TMethods>;
    

    【讨论】:

    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-05
    • 1970-01-01
    • 1970-01-01
    • 2020-08-02
    • 1970-01-01
    • 2015-10-04
    • 2011-12-08
    相关资源
    最近更新 更多