T
T
thehighhomie2021-08-22 15:31:00
Mongoose
thehighhomie, 2021-08-22 15:31:00

Mongoose: typing virtual fields?

I am learning mongodb. I am writing a nestjs + mongoose + typescript application.

I have a constant problem with typing virtual fields.

I will give an example and explain the essence.

For example, there is a user schema:

@Schema({ toJSON: { virtuals: true }, toObject: { virtuals: true } })
export class User {
  @Prop({ required: true })
  email: string;

  @Prop({ required: true })
  password: string;
}


when I get the user's document I have the following structure:
{
  _id: 61205e32ac6ca237401712ec,
  email: '[email protected]',
  __v: 0,
  id: '61205e32ac6ca237401712ec'
}


The first three fields, as I understand it, are real fields that are stored in the database, and the last "id" field is virtual.

So, the problem is that when I get this user object, I set its type to User (from the schema) and there, apart from email and password, no fields are specified anymore, so the typescript starts to swear that the "id" field is not in type User.
612241cf0d645527509081.png

Okay, I went off. to the mongus dock, watch something on the typescript .

The docs say that you can create an interface along with a schema:

interface User {
name: string;
email:string;
avatar?:string;
// maybe add "_id" and "id" fields here for each schema?
}

// 2. Create a Schema corresponding to the document interface.
const schema = new Schema({
name: { type: String, required: true },
email: { type: String, required: true },
avatar: String
});

... and here I thought that it was just possible to add the "_id" and "id" fields to the interface.

But common sense tells me that this is a bad decision, since IDs need to be duplicated in each scheme, and that there should be another solution which I have not been able to find.

Can you please tell me how to solve this properly?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Stockholm Syndrome, 2021-08-22
@StockholmSyndrome

it is possible to inherit from Document, however, in the second paragraph of the same dock page, this is not recommended

import { Document } from "mongoose";

interface User extends Document { /* */ }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question