首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何为猫鼬“Query<any>”添加类型

如何为猫鼬“Query<any>”添加类型
EN

Stack Overflow用户
提问于 2020-11-24 04:02:08
回答 1查看 220关注 0票数 3

我正试图在我的类型记录项目中添加一个缓存层。当我搜索时,我发现了一篇关于媒体的文章

他通过向mongoose.Query.prototype添加一个函数来实现缓存

代码语言:javascript
复制
mongoose.Query.prototype.cache = function(options = { time: 60 }) {
  this.useCache = true;
  this.time = options.time;
  this.hashKey = JSON.stringify(options.key || this.mongooseCollection.name);

  return this;
};

然后在mongoose.Query.prototype.exec中检查是否启用了查询缓存。

代码语言:javascript
复制
mongoose.Query.prototype.exec = async function() {
    if (!this.useCache) {
        return await exec.apply(this, arguments);
    }

    const key = JSON.stringify({
        ...this.getFilter(),
    });
    console.log(this.getFilter());
    console.log(this.hashKey);

    const cacheValue = await client.hget(this.hashKey, key);

    if (cacheValue) {
        const doc = JSON.parse(cacheValue);

        console.log("Response from Redis");
        return Array.isArray(doc)
            ? doc.map((d) => new this.model(d))
            : new this.model(doc);
    }

    const result = await exec.apply(this, arguments);
    return result;
};

现在,通过调用mongoose查询中的cache()函数来启用缓存

代码语言:javascript
复制
 books = await Book.find({ author: req.query.author }).cache();

一切正常,然后我尝试将它转换成类型记录,但我不知道如何为它添加类型定义

打字本版本总是出现错误。

代码语言:javascript
复制
Property 'cache' does not exist on type 'Query<any>',
Property 'useCache' does not exist on type 'Query<any>',
Property 'hashKey' does not exist on type 'Query<any>',

有没有办法将这些类型添加到“查询”中?请帮助我

EN

回答 1

Stack Overflow用户

发布于 2022-08-03 18:42:22

我最终通过以下操作获得了这个效果。还请参见https://stackoverflow.com/a/70656849/1435970

创建文件/src/@types/mongoose.d.ts并向其添加以下内容:

代码语言:javascript
复制
type CacheOptions = {key?: string; time?: number}

declare module 'mongoose' {
  interface DocumentQuery<T, DocType extends import('mongoose').Document, QueryHelpers = {}> {
    mongooseCollection: {
      name: any
    }
    cache(options?: CacheOptions): any
    useCache: boolean
    hashKey: string
  }

  interface Query<ResultType, DocType, THelpers = {}, RawDocType = DocType> extends DocumentQuery<any, any> {}
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64980067

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档