【问题标题】:tsc doesn't recognize virtuals on mongoose schemetsc 无法识别 mongoose 模式中的虚拟对象
【发布时间】:2022-09-29 20:24:04
【问题描述】:

我喜欢猫鼬虚拟,但我不能让它在打字稿中工作。

我正在使用 mongoose 的 InferSchemaType 创建接口,如mongoose documentation 中的“另一种方法:”中所述

TSC 不会将它们识别为界面中的字段。

我尝试了两种建议的方式(参见下面的代码)。

import {connect, InferSchemaType, Schema, model} from \'mongoose\';

const url = \'mongodb://admin:admin@0.0.0.0:27017/\';

export const DBS_Actor = new Schema(
  {
    firstName: String,
    lastName: String,
  },
  {
    virtuals: {
      fullName: {
        get() {
          return this.firstName + \' \' + this.lastName;
        },
      },
    },
  }
);

DBS_Actor.virtual(\'tagname\').get(function () {
  return \'Secrete Agent 007\';
});

export type IActor = InferSchemaType<typeof DBS_Actor>;
export const Actor = model<IActor>(\'User\', DBS_Actor);

run().catch(err => console.log(err));
async function run() {
  await connect(url);

  const actor = new Actor({
    firstName: \'jojo\',
    lastName: \'kiki\',
  });
  await actor.save();
  console.log(actor.toJSON()); // {firstName: \'jojo\', lastName: \'kiki\', _id: new ObjectId(\"62e52b18d41b2bd4d2bd08d8\"),  __v: 0  }
  console.log(actor.firstName); // jojo
  //  console.log(actor.fullname); //TSC error TS2339: Property \'fullname\' does not exist on typ
  //  console.log(actor.tagname); //TSC error TS2339: Property \'tagname\' does not exist on type...
}

    标签: node.js typescript mongoose


    【解决方案1】:

    如果你想在你的类型上使用额外的字段,你可以扩展你的类型:

    export type IActor = InferSchemaType<typeof DBS_Actor> & {
    firstName: String
    };
    

    【讨论】:

      猜你喜欢
      • 2017-02-23
      • 2020-09-16
      • 1970-01-01
      • 2018-03-11
      • 1970-01-01
      • 1970-01-01
      • 2021-02-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多