【问题标题】:Property does not exist on type 'Query'类型“查询”上不存在属性
【发布时间】:2023-01-23 22:18:12
【问题描述】:

我想创建一个 mongoose 模式,我正在尝试向文档添加一个名为 start 的新属性。它在 javascript 中工作,但在 typescript 中,我收到错误消息“类型‘Query<any, any, {}, any>’.ts(2339) 上不存在属性‘start’”。

感谢您为修复错误提供的任何帮助。

import mongoose from 'mongoose';
interface tourSchemaTypes {
  name: string;
}

const tourSchema = new mongoose.Schema<tourSchemaTypes>({
  name: {
    type: String,
    required: [true, 'A tour must have a name'],
    unique: true,
  },
});

const Tour = mongoose.model<tourSchemaTypes>('Tour', tourSchema);

tourSchema.pre(/^find/, function (next) {
  this.find({ secretTour: { $ne: true } });
  this.start = Date.now(); 
  next();
});

tourSchema.post(/^find/, function (docs, next) {
  console.log(`Query took ${Date.now() - this.start} milliseconds`);
  console.log(docs);
  next();
});

【问题讨论】:

    标签: javascript node.js typescript mongoose


    【解决方案1】:

    这在 TypeScript 中不起作用,因为您不能简单地在这些函数的上下文中使用名为 start 的任意键扩展类型为 Query&lt;any, any, {}, any&gt;this

    相反,您可以使用 WeakMap 之类的东西来跟踪您希望为每个查询获得的任何其他信息。

    const queryStartTsMap = new WeakMap<Query<any, any>, number>();
    
    tourSchema.pre(/^find/, function (next) {
      this.find({ secretTour: { $ne: true } });
      queryStartTsMap.set(this, Date.now());
      next();
    });
    
    tourSchema.post(/^find/, function (docs, next) {
      const queryStartTs = queryStartTsMap.get(this);
      if (queryStartTs) {
        console.log(`Query took ${Date.now() - queryStartTs} milliseconds`);
        queryStartTsMap.delete(this);
      }
      console.log(docs);
      next();
    });
    

    【讨论】:

      猜你喜欢
      • 2020-12-11
      • 1970-01-01
      • 2019-09-29
      • 2020-08-08
      • 2021-01-09
      • 2021-07-10
      • 2018-09-07
      • 2018-10-09
      相关资源
      最近更新 更多