静态方法中的上下文丢失
我做错了什么?我有一个架构
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>) { }
}