最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

静态方法中的上下文丢失

运维笔记admin26浏览0评论

静态方法中的上下文丢失

静态方法中的上下文丢失

我做错了什么?我有一个架构

import * as mongoose from 'mongoose';

const PolicySchema = new mongoose.Schema({
  number: { type: 'String', required: true },
  startDate: { type: mongoose.Schema.Types.Date, required: true },
  endDate: { type: mongoose.Schema.Types.Date, required: true },
 ],
});

PolicySchema.statics.lookup = function() {
  console.log(this);
};

export {PolicySchema};

[当我提供服务时,我称此为

@Injectable()
export class PolicyService {
  async test() {
    this.policyModel.schema.statics.lookup();
  }

    constructor(@InjectModel('Policy') private readonly policyModel: Model<Policy>) { }
}

在控制台上,我可以读取我的'This'上下文只是一个{查找:[功能]}我的错误在哪里?在“ This”上,我想获取诸如聚合或获取架构之类的功能。

也许我打错了?请帮助我:)

PS。我使用nest.js

回答如下:

我看了看文档:https://mongoosejs/docs/guide.html#statics

看起来您可以直接在模型上调用static函数。

因此,以上示例应显示为

@Injectable()
export class PolicyService {
  async test() {
    this.policyModel.lookup(); // <== this is the line that changed
  }

    constructor(@InjectModel('Policy') private readonly policyModel: Model<Policy>) { }
}

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论