tsc doesn't recognize virtuals on mongoose scheme

Viewed 56

I love mongoose virtual but I can't make it work in typescript.

I'm using mongoose's InferSchemaType to create the interface as described in "another approach:" in mongoose documentation

TSC doesn't recognize them as a field in the interface.

I tried in both suggested manners (see code below).

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...
}

0 Answers
Related