7

Beginning with typescript I try to declare a Mongoose schema which looks something like this :

User
{
    name : { type: String, required: true },
    ...
    credentials :
    {
        email : { type : String, required : true },
        password : { type : String, required : true },
    },
    ...
}

I've tried this :

import { Document, Types, Schema, Model, model } from "mongoose";

export interface ICredentials
{
    email?:string,
    password?:string,
}

export interface IUser extends Document
{
    name?:string;
    credentials?:ICredentials;
}

export var UserSchema:Schema = new Schema
({
    name            : { type : String, required : true },
    credentials     : 
    {
        email       : { type : String, required : true },
        password    : { type : String, required : true },
    },
});

export const User:Model<IUser> = model<IUser>("User", UserSchema);

The problem when I want to create a new User it seems to work fine. But it has no Credentials. I've tried U.credentials.email = "test@yopmail.com" but it doesn't work. How could I be able to do it ? I'm pretty sure I need to declare a class that implements ICredentials but I'm not familiar with typescript.

T00rk
  • 2,178
  • 3
  • 17
  • 23
  • https://stackoverflow.com/questions/49228020/creating-mongoose-models-with-typescript-subdocuments/55194560#55194560 – aoi umi Mar 16 '19 at 07:52

1 Answers1

0

I faced similar issues recently and here was how I resolved it; I simply added a type assertion..

U.credentials!.email = "test@yopmail.com"
Tron
  • 37
  • 7