node.jstypescriptmongoosetypegoose

Typegoose props not saving


I'm having a problem using typegoose, I have class like:

class UserType1 extends Typegoose
      implements User{
    @prop({required: true, unique: true})
    _username: string | undefined;
    @prop({required: true})
    _password: string | undefined;

    constructor(username:string, password: string){
      this._username = username;
      this._password = password;
    }
    
    async saveToDB(): Promis<void>{ // This method is refrenced inside User Interface
       const model: ModelType<UserType1> = getModelForClass(UserType1);
       await model.create(this);
    }

    <Other methods inside class>
}

Then I use the above code sequence like this:

  const u: User = new UserType1("username", "password");
  u.saveToDB();

then, a new record is saved inside UserType1 collection, but it's empty. non of the _username, _password or other props are saved inside the record. Inside of it there's only _id and a variable called "__v" (which I don't know where it's come from.


Solution

  • Okay, So I left my code and started a new clean one, and It was working perfectly, so I started investigating the difference between codes until I found out this small problem with importing packages, and it was unrelated to my code: Instead of doing

    import {prop} from "@typegoose/typegoose"
    

    I was doing:

    import {prop} from "typegoose"
    

    Since it didn't give me any warning a worked without errors, I never realized this was the problem. Hope this he