【问题标题】:Property 'virtual' does not exist on type 'typeof Schema'“typeof Schema”类型上不存在属性“virtual”
【发布时间】:2018-11-09 21:06:07
【问题描述】:

我正在尝试将 mongoose 架构中的 id 更改为“id”,如此处所示 MongoDB: output 'id' instead of '_id'

复制 ID 字段。

Schema.virtual('id').get(function(){
    return this._id.toHexString();
});

// Ensure virtual fields are serialised.
Schema.set('toJSON', {
    virtuals: true
});

我正在使用打字稿,而 Schema 似乎没有“虚拟”方法或“设置”方法,并且关键字“this”也未绑定在此上下文中。谁知道他们的打字稿等价物?

【问题讨论】:

  • 你从哪里得到你的猫鼬类型定义?确定类型的 v4 d.ts 文件确实在 Schema 类型上提供了“虚拟”函数(github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/…,第 740 行)至于“this”上下文,您可能需要在函数签名中指定类型 .get(function (this: any) { (或者更合适的,如果你知道类型的话)
  • 找到任何解决方案了吗?我面临同样的虚拟问题,这适用于内部功能
  • 请与我们分享您的代码,您的 Schema 已在其中声明
  • 在我看来,您尝试使用的 Schema 对象不是 Mongoose。请检查是否没有其他同名变量。

标签: node.js typescript mongoose


【解决方案1】:

这似乎适用于继承

import { Schema } from 'mongoose';

class BaseSchema extends Schema {
  constructor(args) {
    super();

    this.add(args);

    this.virtual('id').get(function(this: any) {
      return this._id.toHexString();
    });

    this.set('toObject', {
      virtuals: true,
    });

    this.set('toJSON', {
      virtuals: true,
    });
  }
}

【讨论】:

  • 谢谢,这对我也有用。它的好处是您也可以在全球范围内使用它。它返回 _id 和 id。对于只想返回 id 的每个人,其中一个选项是将转换函数应用于 set('toJSON') 方法,如下所示:stackoverflow.com/a/42763286/7372307
猜你喜欢
  • 2021-01-09
  • 1970-01-01
  • 2020-10-04
  • 2020-08-19
  • 2017-11-06
  • 2018-04-26
  • 1970-01-01
  • 2018-09-01
  • 2020-10-14
相关资源
最近更新 更多