首页 > 解决方案 > Express Mongoose 填充 pre typescript 什么类型?

问题描述

我正在将旧的 javascript express 应用程序更新为全新的 typescript 应用程序。我在输入填充时遇到问题

/* 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);

我的 next 和 this 有错误,打字稿指出要输入 any 和 for pre

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

我该如何解决?

标签: typescriptexpressmongoose

解决方案


钩子的参数化类型pre需要是类型Query<ResultType, Doctype extends Document<any, {}>, THelpers={}>

无论您将您的参数化为哪种类型,都IPostSchema应该足以作为此处的 Doctype/ResultType。

例如:

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

您还需要从中Query导入mongoose


推荐阅读