首页 > 解决方案 > “typeof Schema”类型上不存在属性“virtual”

问题描述

我正在尝试将 _id 从 mongoose 模式更改为 'id' 就像这里显示的MongoDB:输出 'id' 而不是 '_id'

复制 ID 字段。

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

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

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

标签: node.jstypescriptmongoose

解决方案


这似乎适用于继承

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,
    });
  }
}

推荐阅读