【问题标题】:Express Mongoose populate pre typescript what type?Express Mongoose 填充 pre typescript 什么类型?
【发布时间】:2021-07-01 03:05:35
【问题描述】:

我正在更新旧的 javascript express 应用 到一个全新的打字稿应用程序。 我在输入 populate 时遇到问题

/* Kind of like a middleware function after creating our schema (since we have access to next) */
/* Must be a function declaration (not an arrow function), because we want to use 'this' to reference our schema */
const autoPopulatePostedBy = function (next) {
  this.populate('postedBy', '_id username avatar');
  this.populate('comments.postedBy', '_id username avatar');
  next();
};

/* We're going to need to populate the 'postedBy' field virtually every time we do a findOne / find query, so we'll just do it as a pre hook here upon creating the schema */
postSchema.pre<IPostSchema>('findOne', autoPopulatePostedBy).pre<IPostSchema>('find', autoPopulatePostedBy);
/* Create index on keys for more performant querying/post sorting */

postSchema.index({ postedBy: 1, createdAt: 1 });

export default model<IPostSchema>('Post', postSchema);

下一个和这个有错误,打字稿指出 为 pre 键入任何 and

Argument of type '"findOne"' is not assignable to parameter of type 'RegExp | MongooseDocumentMiddleware | MongooseDocumentMiddleware[]'

我该如何解决?

【问题讨论】:

    标签: typescript express mongoose


    【解决方案1】:

    pre 挂钩的参数化类型必须是 Query&lt;ResultType, Doctype extends Document&lt;any, {}&gt;, THelpers={}&gt; 类型

    您将IPostSchema 参数化为的任何类型都应该足以作为此处的Doctype/ResultType。

    例如:

    postSchema.pre<Query<IPostInterfaceDocument, IPostInterfaceDocument>>('findOne', .....
    

    您还需要从mongoose 导入Query。

    【讨论】:

      猜你喜欢
      • 2015-08-07
      • 1970-01-01
      • 2020-05-02
      • 2019-06-25
      • 1970-01-01
      • 2021-03-19
      • 2014-11-27
      • 2017-09-25
      • 1970-01-01
      相关资源
      最近更新 更多